检查模板参数是否属于类类型?

NEW*_*BIE 7 c++ templates

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

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
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*rav 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
}
Run Code Online (Sandbox Code Playgroud)

产量

101
Run Code Online (Sandbox Code Playgroud)

  • @Prasoon Saurav ......很好的解决方案!我喜欢它! (2认同)