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
调用会触发静态断言。