名前空間
変種
操作

std::integral_constant

From cppreference.com
< cpp‎ | types
 
 
メタプログラミングライブラリ
型特性
型のカテゴリ
(C++11)
(C++11)(DR*)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11) 
(C++11)
(C++11)
型のプロパティ
(C++11)
(C++11)
(C++14)
(C++11)(C++26で非推奨)
(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++23で非推奨)
(C++11)(C++23で非推奨)
(C++11)
(C++11)(C++20まで*)(C++17)

(C++11)
(C++17)
コンパイル時有理数演算
コンパイル時整数シーケンス
 
ヘッダ <type_traits> で定義
template< class T, T v >
struct integral_constant;
(C++11以降)

std::integral_constant は、指定された型の静的定数をラップします。これは C++ の型特性の基底クラスです。

プログラムが std::integral_constant の特殊化を追加した場合、その動作は未定義です。

目次

[編集] ヘルパーエイリアステンプレート

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
[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() {}

[編集] 関連項目

コンパイル時の整数シーケンスを実装する
(クラステンプレート) [編集]
English 日本語 中文(简体) 中文(繁體)