std::integral_constant

出自cppreference.com
 
 
元編程庫
類型特徵
類型類別
(C++11)
(C++11)(DR*)
(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++26 棄用)
(C++11)(C++20 前*)
(C++11)(C++20 棄用)
(C++11)
類型特徵常量
元函數
(C++17)
受支持操作
關係與屬性查詢
類型修改
(C++11)(C++11)(C++11)
類型變換
(C++11)(C++23 棄用)
(C++11)(C++23 棄用)
(C++11)
(C++11)(C++20 前*)(C++17)

(C++11)
(C++17)
編譯時有理數算術
編譯時整數序列
 
在標頭 <type_traits> 定義
template< class T, T v >
struct integral_constant;
(C++11 起)

std::integral_constant 包裝特定類型的靜態常量。它是 C++ 類型特徵的基類。

如果程序添加了 std::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>

成員常量

名字
value
[靜態]
v
(公開靜態成員常量)

成員函數

返回包裝的值
(公開成員函數) [編輯]
返回包裝的值
(公開成員函數) [編輯]

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 起
};

註解

功能特性測試 標準 功能特性
__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() {}

參閱

實現編譯時整數數列
(類模板) [編輯]