Namespaces
Variants

std:: integral_constant

From cppreference.net
Metaprogramming library
Type traits
Type categories
(C++11)
(C++11) ( DR* )
Type properties
(C++11)
(C++11)
(C++14)
(C++11) (deprecated in C++26)
(C++11) ( until C++20* )
(C++11) (deprecated in C++20)
(C++11)
Type trait constants
integral_constant bool_constant true_type false_type
(C++11) (C++17) (C++11) (C++11)
Metafunctions
(C++17)
Supported operations
Relationships and property queries
Type modifications
Type transformations
(C++11) (deprecated in C++23)
(C++11) (deprecated in C++23)
(C++11)
(C++11) ( until C++20* ) (C++17)

Compile-time rational arithmetic
Compile-time integer sequences
定义于头文件 <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 的常见情况提供了两种类型定义:

定义于头文件 <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 ;
(since 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; // 使用注入类名
    constexpr operator value_type() const noexcept { return value; }
    constexpr value_type operator()() const noexcept { return value; } // 自 C++14 起
};

注释

功能测试 标准 功能
__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() {}

另请参阅

实现编译期整数序列
(类模板)