std::integral_constant
出自cppreference.com
| 在標頭 <type_traits> 定義
|
||
| |
(C++11 起) | |
std::integral_constant 包裝特定類型的靜態常量。它是 C++ 類型特徵的基類。
如果程序添加了 std::integral_constant 的特化,那麼行為未定義。
輔助別名模板
針對 T 是 bool 的常用情況定義輔助別名模板 std::bool_constant。
| |
(C++17 起) | |
特化
針對 T 是 bool 的兩種常用情形提供 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 (公開靜態成員常量) |
成員函數
| 返回包裝的值 (公開成員函數) | |
(C++14) |
返回包裝的值 (公開成員函數) |
std::integral_constant::operator value_type
| |
||
轉換函數。返回包裝的值。
std::integral_constant::operator()
| |
(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() {}
參閱
(C++14) |
實現編譯時整數數列 (類模板) |