integral_constant定义编译期常量

#include  "stdafx.h"
#include <iostream>
#include <type_traits>
 
using  namespace   std;
 
/*
integral_constant就可方便地定义编译期常量,而无需再通过enum和static const变量方式,这也为定义编译期常量提供另一种方法。
integral_constant类 是所有traits类的基类,分别提供了以下功能:
  
value_type 表示值的类型
value表示值
type 表示自己, 因此可以用::type::value来获取值
true_type和false_type两个特化类用来表示bool值类型的traits,很多traits类都需要继承它们

 


template<class _Ty, _Ty _Val>
struct integral_constant
{
// convenient template for integral constant types
static _CONST_DATA _Ty value = _Val;

typedef  _Ty    value_type;

typedef integral_constant<_Ty, _Val>   type;

_CONST_FUN operator value_type() const _NOEXCEPT
{
return (value);// return stored value
}

_CONST_FUN value_type operator()() const _NOEXCEPT
{
return (value);// return stored value
}
};

typedef integral_constant<bool, true> true_type;
typedef integral_constant<bool, false> false_type;


// ALIAS TEMPLATE bool_constant
template<bool _Val>
using bool_constant = integral_constant<bool, _Val>;

*/
 


template <unsigned n>
struct factorial :  integral_constant<int ,    n * factorial<n - 1>::value>
{


};


template <>//特化
struct factorial<0> : integral_constant<int,  1>
{
};






int main()
{
typedef     integral_constant<int, 111>     IC;


cout << "value " << IC::value << endl;
cout << "value_type   " << typeid(IC::value_type).name() << endl;
cout << "type  " << typeid(IC::type).name() << endl;


IC   ic;




int   c1 = ic;  //调用的operator value_type() 
cout << c1 << endl;


int  c2 = ic();//调用的 operator()() 
cout << c1 << endl;




cout << integral_constant<char,  'a'>::value <<endl; 


/*
非型别模版参数必须是整型或者和整型兼容的,  double和float不行
cout << integral_constant<double, 12.23>::value << endl;
cout << integral_constant<float, 12.23f>::value << endl;
*/




cout << true_type::value << endl; 
 
cout << bool_constant <false>::value << endl;


cout << factorial<5>::value<<endl;  // constexpr (no calculations on runtime)


}


Created  By   黄强


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值