std::integral_constant
提供: cppreference.com
ヘッダ <type_traits> で定義 | ||
template<class T, T v > struct integral_constant; | (C++11以上) | |
std::integral_constant は指定された型の static な定数をラップします。 これは C++ の型特性のための規定クラスです。
ヘルパーテンプレート
| (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 [静的] | 値 v を持つ型 T の static な定数 (パブリック静的メンバ定数) |
[編集]メンバ関数
operator value_type | ラップされた値を返します (パブリックメンバ関数) |
operator() (C++14) | ラップされた値を返します (パブリックメンバ関数) |
std::integral_constant::operator value_type
constexpr operator value_type()constnoexcept; | ||
変換関数。 ラップされた値を返します。
std::integral_constant::operator()
constexpr value_type operator()()constnoexcept; | (C++14以上) | |
ラップされた値を返します。 この関数は std::integral_constant をコンパイル時関数オブジェクトのソースとして使用できるようにします。
[編集]実装例
template<class T, T v>struct integral_constant {staticconstexpr T value = v;using value_type = T;using type = integral_constant;// using injected-class-nameconstexpr operator value_type()constnoexcept{return value;}constexpr value_type operator()()constnoexcept{return value;}//since c++14}; |
[編集]例
Run this code
#include <iostream>#include <type_traits> int main(){typedef std::integral_constant<int, 2> two_t;typedef std::integral_constant<int, 4> four_t; // static_assert(std::is_same<two_t, four_t>::value,// "two_t and four_t are not equal!"); // error: static assertion failed: "two_t and four_t are not equal!" static_assert(two_t::value*2== four_t::value, "2*2 != 4"); enumclass my_e { e1, e2 };typedef std::integral_constant<my_e, my_e::e1> my_e_e1;typedef std::integral_constant<my_e, my_e::e2> my_e_e2; // static_assert(my_e_e1::value == my_e::e2,// "my_e_e1::value != my_e::e2");// error: static assertion failed: "my_e_e1::value != my_e::e2" static_assert(std::is_same<my_e_e2, my_e_e2>::value, "my_e_e2 != my_e_e2");}