在线文档教程
C++
应用 | Utilities

std::integral_constant

STD:积分[医]常量

Defined in header
template< class T, T v > struct integral_constant;(since C++11)

std::integral_constant包装指定类型的静态常量。它是C++类型特征的基类。

Helper templates A helper alias template std::bool_constant is defined for the common case where T is bool. template using bool_constant = integral_constant;template using bool_constant = integral_constant;(since C++17)
template <bool B> using bool_constant = integral_constant<bool, B>;

两种类型用于常见情况Tbool提供:

在标头<type中定义[医]性状>

*。

类型定义

千真万确[医]STD类型::整型[医]常数<bool,true>

假的[医]STD类型::整型[医]常数<bool,false>

成员类型

TypeDefinition
value_typeT
typestd::integral_constant<T,v>

成员常数

NameValue
constexpr T value staticstatic constant of type T with value v (public static member constant)

成员函数

operator value_typereturns the wrapped value (public member function)
operator() (C++14)returns the wrapped value (public member function)

STD:积分[医]常数::运算符值[医]类型

constexpr operator value_type() const;

转换函数。返回包装的值。

例外

noexcept规格:

noexcept

STD:积分[医]常数::运算符%28%29

constexpr value_type operator()() const;(since C++14)

返回包装的值。此函数启用std::integral_constant作为编译时函数对象的来源。

例外

noexcept规格:

noexcept

可能的实施

模板<类T,Tv>结构积分[医]常数{静态常数T值=v;[医]类型[医]常量类型;//使用注入的类名称conexpr运算符值[医]类型%28%29 const no{返回值除外;}constexpr值)[医]类型运算符%28%29%28%29 const no除{返回值;}//自c++14};

*。

二次

#include <iostream> #include <type_traits> int main() { typedef std::integral_constant<int, 2> two_t; typedef std::integral_constant<int, 4> four_t; // static_assert(std::is_same<two_t, four_t>::value, // "two_t and four_t are not equal!" // error: static assertion failed: "two_t and four_t are not equal!" static_assert(two_t::value*2 == four_t::value, "2*2 != 4" enum class my_e { e1, e2 }; typedef std::integral_constant<my_e, my_e::e1> my_e_e1; typedef std::integral_constant<my_e, my_e::e2> my_e_e2; // static_assert(my_e_e1::value == my_e::e2, // "my_e_e1::value != my_e::e2" // error: static assertion failed: "my_e_e1::value != my_e::e2" static_assert(std::is_same<my_e_e2, my_e_e2>::value, "my_e_e2 != my_e_e2" }

二次

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/type/Integral[医]常量