名前空間
変種
操作

std::integral_constant

提供: cppreference.com
< cpp‎ | types
 
 
ユーティリティライブラリ
汎用ユーティリティ
日付と時間
関数オブジェクト
書式化ライブラリ (C++20)
(C++11)
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)
スワップと型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
一般的な語彙の型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等文字列変換
(C++17)
(C++17)
 
型サポート
型の性質
(C++11)
(C++11)
(C++14)
(C++11)
(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++11)
(C++17)
(C++11)(C++20未満)(C++17)
 
ヘッダ <type_traits> で定義
template< class T, T v >
struct integral_constant;
(C++11以上)

std::integral_constant は指定された型の static な定数をラップします。 これは C++ の型特性のための規定クラスです。

目次

ヘルパーテンプレート

Tbool である一般的なケースのためにヘルパーエイリアステンプレート std::bool_constant が定義されます。

template <bool B>
using bool_constant = integral_constant<bool, B>;
(C++17以上)

Tbool である一般的なケースのために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
ラップされた値を返します
(パブリックメンバ関数) [edit]
operator()
(C++14)
ラップされた値を返します
(パブリックメンバ関数) [edit]

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

[編集]

#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"
    );
 
    enum class 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");
}