CppDS.com

C++ 98 11 14 17 20 手册

std::integral_constant

来自cppreference.com
< cpp‎ | types
 
 
工具库
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)
swap 与类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等字符串转换
(C++17)
(C++17)
 
类型支持
基本类型
基础类型
定宽整数类型 (C++11)
数值极限
C 数值极限接口
运行时类型信息
类型特性
类型类别
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
类型属性
(C++11)
(C++11)
(C++14)
(C++11)
(C++11)(C++20 前)
(C++11)(C++20 中弃用)
(C++11)
类型特性常量
integral_constantbool_constanttrue_typefalse_type
(C++11)(C++17)(C++11)(C++11)
元函数
(C++17)
常量求值语境
受支持操作
关系与属性查询
类型修改
(C++11)(C++11)(C++11)
类型变换
(C++11)
(C++11)
(C++17)
(C++11)(C++20 前)(C++17)
 
定义于头文件 <type_traits>
template< class T, T v >
struct integral_constant;
(C++11 起)

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

添加 integral_constant 的特化的程序行为未定义。

辅助模板

Tbool 的常用情况定义辅助别名模板 std::bool_constant

template <bool B>
using bool_constant = integral_constant<bool, B>;
(C++17 起)

为其中 Tbool 的二种常用情形提供 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
[静态]
T 类型的值为 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; // 使用注入类名
    constexpr operator value_type() const noexcept { return value; }
    constexpr value_type operator()() const noexcept { return value; } // 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_e1, my_e_e2>::value,
                  "my_e_e1 != my_e_e2");
}


关闭