std::integral_constant
From 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以降) | |
[編集] 特殊化
T が bool である一般的なケースのために、2つの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 [static] |
v (公開静的メンバ定数) |
[編集] メンバ関数
| 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) |
コンパイル時の整数シーケンスを実装する (クラステンプレート) |