Namespaces
Variants

std:: integral_constant

From cppreference.net
Metaprogramming library
Type traits
Type categories
(C++11)
(C++11) ( DR* )
Type properties
(C++11)
(C++11)
(C++14)
(C++11) (deprecated in C++26)
(C++11) ( until C++20* )
(C++11) (deprecated in C++20)
(C++11)
Type trait constants
integral_constant bool_constant true_type false_type
(C++11) (C++17) (C++11) (C++11)
Metafunctions
(C++17)
Supported operations
Relationships and property queries
Type modifications
Type transformations
(C++11) (deprecated in C++23)
(C++11) (deprecated in C++23)
(C++11)
(C++11) ( until C++20* ) (C++17)

Compile-time rational arithmetic
Compile-time integer sequences
ヘッダーで定義 <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
ラップされた値を返す
(公開メンバ関数)
operator()
(C++14)
ラップされた値を返す
(公開メンバ関数)

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; // 注入クラス名の使用
    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() {}

関連項目

整数のコンパイル時シーケンスを実装する
(クラステンプレート)