2010-12-04 76 views
7

如何使用一些模板检查传递的模板参数是否是类类型?检查模板参数是否是类类型?

int main() 
{ 
    CheckIfClass<int>::checkConst ; No it is not of a class type 
    class CLASS{}; 
    CheckIfClass<CLASS>::checkConst ; Yes CLASS is a class. 
    CheckIfClass<std::string>::checkConst ; Yes std::string is a class 
} 
+0

为什么你需要知道? – 2010-12-04 06:29:46

回答

7

SFINAE应该做你的工作

#include <iostream> 
template<typename T> 
struct Check_If_T_Is_Class_Type 
{ 
    template<typename C> static char func (char C::*p); 
    template<typename C> static int func (...); 
    enum{val = sizeof (Check_If_T_Is_Class_Type<T>::template func<T>(0)) == 1}; 
}; 
class empty{}; // Defined the class in the global namespace. 
       // You can't have local classes as template arguments in C++03 

int main() 
{ 

    std::cout<<Check_If_T_Is_Class_Type<empty>::val; // 1 
    std::cout<<Check_If_T_Is_Class_Type<int>::val; // 0 
    std::cout<<Check_If_T_Is_Class_Type<std::string>::val; //1 
} 

Output

101 
+0

@Saurav:第7行:错误C2056:非法表达 – bjskishore123 2010-12-04 06:40:59

+0

@UpVoter:Oh ideone以C++ 0x模式编译代码。更新了我的答案(对于C++ 03)。 – 2010-12-04 06:46:29

2

的C++ 0x提供了一个非常简单的解决方案:

#include <iostream> 
#include <type_traits> 

int main() 
{ 
    std::cout << is_class<your_type_here>::value << std::endl; 
} 
1

使用MSVC++ 08编译的代码,以及GCC,Comeau和Clang(已编辑)。

#include <iostream> 
template<typename T> 
struct Check_If_T_Is_Class_Type 
{ 
    template<typename C> static char func (char C::*p); 
    template<typename C> static int func (...); 
    enum{val = sizeof (func<T>(0)) == 1}; 
}; 
class empty{}; 
int main() 
{ 
    std::cout<<Check_If_T_Is_Class_Type<empty>::val; // 1 
    std::cout<<Check_If_T_Is_Class_Type<int>::val; // 0 
    std::cout<<Check_If_T_Is_Class_Type<std::string>::val; //1 
} 

@Prasoon ...请你编译这个在科莫,以及锵......并告诉我,如果它被编译或不?谢谢!

相关问题