利用模板判断模板参数类型

C++中可以把数据类型当成参数,类型参数可以由编译器推导出来,也可以由程序员显式指定. 下面的两个模板,就可以用来判断模板的类型参数是否为reference或者const.

template <typename T> struct IsReference ///Use this struct to determine if a template type is a reference { enum { VALUE = 0 }; };

template <typename T> struct IsReference<T&> { enum { VALUE = 1 }; };

template <typename T> struct IsReference<const T&> { enum { VALUE = 1 }; };

template <typename T> struct IsConst ///Use this struct to determine if a template type is a const type { enum { VALUE = 0 }; };

template <typename T> struct IsConst<const T&> { enum { VALUE = 1 }; };

template <typename T> struct IsConst<const T> { enum { VALUE = 1 }; };

这两个模板函数(IsReference和IsConst)聪明的地方在于,编译器会根据模板参数的类型,选 择最贴近的模板类(struct)来实例化.

使用示例: template <typename T> void foo() { if (IsReferenc<T>.VALUE) { // 类型参数T为reference } if (IsConst<T>.VALUE) { // 类型参数为const } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值