名稱空間
變體
操作

std::integral_constant

來自 cppreference.com
< cpp‎ | 型別
 
 
超程式設計庫
型別特性
型別類別
(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)
型別特性常量
integral_constantbool_constanttrue_typefalse_type
(C++11)(C++17)(C++11)(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 起)

[編輯] 特化

提供了兩個 typedef 用於 Tbool 的常見情況

定義於標頭檔案 <type_traits>
名稱 定義
true_type std::integral_constant<bool, true>
false_type std::integral_constant<bool, false>

[編輯] 成員型別

名稱 定義
value_type T
型別 std::integral_constant<T, v>

[編輯] 成員常量

名稱
constexpr T value
[靜態]
v
(public static 成員常量)

[編輯] 成員函式

operator value_type
返回包裝的值
(public member function) [編輯]
operator()
(C++14)
返回包裝的值
(public member function) [編輯]

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

[編輯] 注意

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

[編輯] 參閱

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