如何在忽略模板参数的同时确定类类型。
所以对于像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>
答案 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