如何检查忽略其模板参数的类型

时间:2014-05-27 03:06:09

标签: c++ templates template-meta-programming typetraits

如何在忽略模板参数的同时确定类类型。

所以对于像MyClass<param1, param2, ...>这样的完全指定的类型,我想检查它是否确实是MyClass类型?

的精神
typedef ClassName<param1, param2, ...> T;

//Now my program receives T which can be any arbitrary type
//and I want to have something like the following
//check_if_MyClassType<T>::value should be true
//check_if_MyClassType<int>::value should be false
//check_if_MyClassType<T>::value should be false if T is not a MyClass type e.g T = vector<int>

2 个答案:

答案 0 :(得分:3)

template <class T>
struct IsClassName { static const bool value = false; };

template <class param1, param2, ...>
struct IsClassName<ClassName<param1, param2, ...> > { static const bool value = true; };

答案 1 :(得分:1)

我认为这就是你要找的东西。

#include <iostream>
#include <vector>

template <typename T>
struct IsMyClassType { static const bool value = false; };

template <typename T> struct MyClass {};

template <typename T>
struct IsMyClassType<MyClass<T> > { static const bool value = true; };

测试上面的代码......

int main()
{
   std::cout << IsMyClassType<int>::value << std::endl;
   std::cout << IsMyClassType<MyClass<int> >::value << std::endl;
   std::cout << IsMyClassType<MyClass<float> >::value << std::endl;
   std::cout << IsMyClassType<MyClass<std::vector<float> > >::value << std::endl;

   return 0;
}

输出:

0
1
1
1