其他的一些

1 integral_constant

大部分类型特性都会使用到的。作用:用来存储一个特定类型的编译时常量

  • 下面这部分代码为 integral_constant定义,其他的都是特例化版本。
    value_type为常量的类型
    value为存储的编译时常量的值
  template<typename _Tp, _Tp __v>                  
    struct integral_constant
    {
      static constexpr _Tp                  value = __v;
      typedef _Tp                           value_type;
      typedef integral_constant<_Tp, __v>   type;
      constexpr operator value_type() const noexcept { return value; }
#if __cplusplus > 201103L

#define __cpp_lib_integral_constant_callable 201304

      constexpr value_type operator()() const noexcept { return value; }
#endif
    };

bool类型特化版本

  /// The type used as a compile-time boolean with true value.      
  using true_type =  integral_constant<bool, true>;

  /// The type used as a compile-time boolean with false value.
  using false_type = integral_constant<bool, false>;

 template<bool __v>
    using __bool_constant = integral_constant<bool, __v>;
  /// @endcond

#if __cplusplus >= 201703L
# define __cpp_lib_bool_constant 201505
  /// Alias template for compile-time boolean constant types.
  /// @since C++17
  template<bool __v>
    using bool_constant = integral_constant<bool, __v>;

2 declval

用来在decltype中进行类型推导

  • decltype函数模板的定义如下
  template<typename _Tp>                     
    auto declval() noexcept -> decltype(__declval<_Tp>(0))
    {
      static_assert(__declval_protector<_Tp>::__stop,
		    "declval() must not be used!");
      return __declval<_Tp>(0);
    }

有一点需要特别注意declval 只能用于decltype推导。如果在其他地方使用,会触发静态断言。

  • __declval_protector定义如下 :就是把 false封装了一层
  template<typename _Tp> 
    struct __declval_protector
    {
      static const bool __stop = false;
    };

declval在不同的上下文会表现出不同行为的原因是:

  • 在 decltype 中使用,实际上并不会调用declval,只用作类型推导。
  • 如果在其他地方使用,declval调用会触发静态断言。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值