检查模板参数是否是类类型? [英] Checking whether a template argument is of a class type?

查看:160
本文介绍了检查模板参数是否是类类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to check using some template hack whether a template argument passed is of class type?

示例

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
}


推荐答案

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
}

输出

101

这篇关于检查模板参数是否是类类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆