[C++] How do I check my template class is of a specific classtype?


Answers

Instead of checking for the type use specializations. Otherwise, don't use templates.

template<class T> int foo(T a) {
      // generic implementation
}
template<> int foo(SpecialType a) {
  // will be selected by compiler 
}

SpecialType x;
OtherType y;
foo(x); // calls second, specialized version
foo(y); // calls generic version
Question

In my template-ized function, I'm trying to check the type T is of a specific type. How would I do that?

p/s I knew the template specification way but I don't want to do that.

template<class T> int foo(T a) {
  // check if T of type, say, String?
}

Thanks!




If you don't care about compile-time, you may use boost::is_same.

bool isString = boost::is_same<T, std::string>::value;

As of C++11, this is now part of the standard library

bool isString = std::is_same<T, std::string>::value



You could do it like this:

#include <typeinfo>
...
template<class A, class B>
struct ADD {

    static inline int comp_b(int v){
        // HERE check if class A is LIT  or VAL_x
        std::cout << ( typeid(A)==typeid(VAL_x) ) << '\n';
        return 2;
    };
};

where I am using std::type_info, which will print 1, for true evaluation.

Or, with c++11, you could do:

#include <type_traits>
...
if (std::is_same<A, VAL_x>::value)
    std::cout << "they are same!\n";

However, you could overload a function or such. Make sure you read this: How do I check my template class is of a specific classtype? and this How to check for the type of a template parameter?




How do I check my template class is of a specific classtype?

I suppose you could use the std::type_info returned by the typeid operator