std::integral_constant
來自 cppreference.com
定義於標頭檔案 <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 起) | |
[編輯] 特化
提供了兩個 typedef 用於 T
為 bool 的常見情況
定義於標頭檔案
<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() {}
[編輯] 參閱
(C++14) |
實現編譯時整數序列 (類模板) |