How do I check my template class is of a specific

2020-02-10 02:28发布

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!

标签: c++ templates
8条回答
劫难
2楼-- · 2020-02-10 03:20

hmm because I had a large portion of same code until the 'specification' part.

You can use overloading, but if a large part of the code would work for any type, you might consider extracting the differing part into a separate function and overload that.

template <class T>
void specific(const T&);

void specific(const std::string&);

template <class T>
void something(const T& t)
{
    //code that works on all types
    specific(t);
    //more code that works on all types
}
查看更多
来,给爷笑一个
3楼-- · 2020-02-10 03:21

I suspect someone should tell you why it might not be a good idea to avoid using overloading or specialization. Consider:

template<class T> int foo(T a) {
  if(isAString<T>()) {
    return a.length();
  } else {
    return a;
  }
}

You might think on a first sight that it will work for int too, because it will only try to call length for strings. But that intuition is wrong: The compiler still checks the string branch, even if that branch is not taken at runtime. And it will find you are trying to call a member function on non-classes if T is an int.

That's why you should separate the code if you need different behavior. But better use overloading instead of specialization, since it's easier to get a clue how things work with it.

template<class T> int foo(T a) {
  return a;
}

int foo(std::string const& a) {
  return a.length();
}

You have also better separated the code for different paths of behavior. It's not all anymore clued together. Notice that with overloading, the parameters may have different type forms and the compiler will still use the correct version if both match equally well, as is the case here: One can be a reference, while the other can not.

查看更多
登录 后发表回答