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条回答
▲ chillily
2楼-- · 2020-02-10 02:55

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

查看更多
何必那么认真
3楼-- · 2020-02-10 02:59

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
查看更多
家丑人穷心不美
4楼-- · 2020-02-10 03:01

You can perform static checks on the type that you have received (look at the boost type traits library), but unless you use specialization (or overloads, as @litb correctly points out) at one point or another, you will not be able to provide different specific implementations depending on the argument type.

Unless you have a particular reason (which you could add to the question) not to use the specialization in the interface just do specialize.

template <> int subtract( std::string const & str );
查看更多
相关推荐>>
5楼-- · 2020-02-10 03:05

If you are using C++11 or later, std::is_same does exactly what you want:

template <typename T>
constexpr bool IsFloat() { return std::is_same<T, float>::value; }

template <typename T>
void SomeMethodName() {
  if (IsFloat<T>()) {
    ...
  }
}

http://en.cppreference.com/w/cpp/types/is_same

查看更多
6楼-- · 2020-02-10 03:08

You can check using type_traits (available in Boost and TR1) (e.g. is_same or is_convertible) if you really want to avoid specialization.

查看更多
Viruses.
7楼-- · 2020-02-10 03:12

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
查看更多
登录 后发表回答