Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

template<class T> int foo(T a) {
  // check if T of type, say, String?
}
like image 395
huy Avatar asked Sep 11 '25 02:09

huy


2 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
like image 184
dirkgently Avatar answered Sep 12 '25 17:09

dirkgently


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
like image 27
Benoît Avatar answered Sep 12 '25 17:09

Benoît