Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
#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 << ") "; } }; int main() { std::cout << TypeInfo<int>::name() << " "; // int std::cout << TypeInfo<double>::name() << " "; // double std::cout << TypeInfo<int*>::name() << " "; // int* std::cout << TypeInfo<float>::name() << " "; // unknown std::cout << std::boolalpha << TypeInfo<int*>::isPointer() << " "; // true Pair<std::string, int> p("age", 30); p.print(); return 0; }
Result
Open