C++ integral_constant 实现
integral_constant 是模板元编程的一个重要的类, 它的作用是定义类型的常量. 它定义了 bool_constant, true_type 和 false_type.
注意: 本人是原创, 如若发现雷同, 后果自负
作用
C++ 17 之前由于没有变量模板, 我们需要获取结果会使用::value 比如: (is_empty<int>::value), 其实就是继承自integral_constant, 例如 is_same 的实现:
template <typename, typename>
struct is_same
: public false_type
{};
template <typename T
>
struct is_same
<T
, T
> : public false_type
{};
实现
integral_constant
template <typename T
, T Var
>
struct integral_constant
{
using type
= T
;
using value_type
= integral_constant
;
static constexpr T value
= Var
;
constexpr operator value_type() const noexcept { return value
; }
constexpr value_type
operator()() const noexcept { return value
; }
}
true_type
using true_type
= integral_constant
<bool, true>;
false_type
using false_type
= integral_constant
<bool, false>;
这样实现其它的会更简单.
上一篇: 实现STL type_traits 头文件 QQ交流群: 552641067