C++
Beginner
1 min read
Class Templates and Template Specialisation
Example
#include <iostream>
#include <string>
// Primary class template
template<typename T>
class TypeInfo {
public:
static std::string name() { return "unknown"; }
static bool isPointer() { return false; }
};
// Full specialisation for int
template<>
class TypeInfo<int> {
public:
static std::string name() { return "int"; }
static bool isPointer() { return false; }
};
// Full specialisation for double
template<>
class TypeInfo<double> {
public:
static std::string name() { return "double"; }
static bool isPointer() { return false; }
};
// Partial specialisation for any pointer type
template<typename T>
class TypeInfo<T*> {
public:
static std::string name() { return TypeInfo<T>::name() + "*"; }
static bool isPointer() { return true; }
};
// Generic Pair class template
template<typename First, typename Second>
class Pair {
public:
Pair(First f, Second s) : first(f), second(s) {}
First first;
Second second;
void print() const {
std::cout << "(" << first << ", " << second << ")\n";
}
};
int main() {
std::cout << TypeInfo<int>::name() << "\n"; // int
std::cout << TypeInfo<double>::name() << "\n"; // double
std::cout << TypeInfo<int*>::name() << "\n"; // int*
std::cout << TypeInfo<float>::name() << "\n"; // unknown
std::cout << std::boolalpha
<< TypeInfo<int*>::isPointer() << "\n"; // true
Pair<std::string, int> p("age", 30);
p.print();
return 0;
}