std::integral_constant
来自 cppreference.cn
定义于头文件 <type_traits> |
||
template< class T, T v > struct integral_constant; |
(自 C++11 起) | |
std::integral_constant
封装一个指定类型的静态常量。它是 C++ 类型特征的基类。
如果程序为 std::integral_constant
添加特化,则行为未定义。
内容 |
[编辑] 辅助别名模板
为 T
为 bool 的常见情况定义了辅助别名模板 std::bool_constant
。
template< bool B > using bool_constant = integral_constant<bool, B>; |
(自 C++17 起) | |
[编辑] 特化
为 T
为 bool 的常见情况提供了两个 typedef
定义于头文件
<type_traits> | |
名称 | 定义 |
true_type
|
std::integral_constant<bool, true> |
false_type
|
std::integral_constant<bool, false> |
[编辑] 成员类型
名称 | 定义 |
value_type
|
T |
type
|
std::integral_constant<T, v> |
[编辑] 成员常量
名称 | 值 |
constexpr T value [静态] |
v (公有静态成员常量) |
[编辑] 成员函数
operator value_type |
返回封装的值 (公有成员函数) |
operator() (C++14) |
返回封装的值 (公有成员函数) |
std::integral_constant::operator value_type
constexpr operator value_type() const noexcept; |
||
转换函数。 返回封装的值。
std::integral_constant::operator()
constexpr value_type operator()() const noexcept; |
(自 C++14 起) | |
返回封装的值。 此函数使 std::integral_constant
可以充当编译时函数对象的来源。
[编辑] 可能的实现
template<class T, T v> struct integral_constant { static constexpr T value = v; using value_type = T; using type = integral_constant; // using injected-class-name constexpr operator value_type() const noexcept { return value; } constexpr value_type operator()() const noexcept { return value; } // since c++14 }; |
[编辑] 注解
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_integral_constant_callable |
201304L |
(C++14) | std::integral_constant::operator()
|
__cpp_lib_bool_constant |
201505L |
(C++17) | std::bool_constant
|
[编辑] 示例
运行此代码
#include <type_traits> using two_t = std::integral_constant<int, 2>; using four_t = std::integral_constant<int, 4>; static_assert(not std::is_same_v<two_t, four_t>); static_assert(two_t::value * 2 == four_t::value, "2*2 != 4"); static_assert(two_t() << 1 == four_t() >> 0, "2*2 != 4"); enum class E{ e1, e2 }; using c1 = std::integral_constant<E, E::e1>; using c2 = std::integral_constant<E, E::e2>; static_assert(c1::value != E::e2); static_assert(c1() == E::e1); static_assert(std::is_same_v<c2, c2>); int main() {}
[编辑] 参见
(C++14) |
实现编译时整数序列 (类模板) |