CKTIS / C++
std::integral_constant — eine Konstante als Typ
std::integral_constant<T, v> stellt die Konstante v vom Typ T als Typ dar. Der Header <type_traits> stellt außerdem std::bool_constant, std::true_type und std::false_type bereit, um boolesche Ergebnisse in der Metaprogrammierung auszudrücken.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <type_traits>
// Synopsis only: the header provides these declarations.
namespace std {
template<class T, T v> struct integral_constant;
template<bool B> using bool_constant = integral_constant<bool, B>;
using true_type = bool_constant<true>;
using false_type = bool_constant<false>;
}std::integral_constant<T, v> aus <type_traits> verknüpft die Konstante v vom Typ T mit einem Typ. Sie ist ein grundlegender Baustein der Type-Traits-Schnittstelle: Ein Ergebnis lässt sich als Typ statt nur als Wert weitergeben.
Das Member value ist ein static constexpr T und gleich v; value_type bezeichnet T, und type bezeichnet die Spezialisierung std::integral_constant<T, v> selbst. Ein Objekt stellt eine implizite Konvertierung zu value_type und einen operator() bereit. Beide sind constexpr und noexcept und geben value zurück.
std::bool_constant<B> ist ein Alias für std::integral_constant<bool, B>. std::true_type und std::false_type bezeichnen jeweils std::bool_constant<true> und std::bool_constant<false>; es sind Typen, keine booleschen Variablen. Der Syntaxabschnitt zeigt beispielhafte Deklarationen – binde den Header ein, statt diese Namen selbst zu deklarieren.
Beispiele
#include <iostream>
#include <type_traits>
int main() {
using Answer = std::integral_constant<int, 42>;
using Positive = std::bool_constant<(Answer::value > 0)>;
static_assert(std::is_same_v<Answer::value_type, int>);
static_assert(std::is_same_v<Answer::type, Answer>);
static_assert(std::is_same_v<Positive, std::true_type>);
static_assert(!std::false_type::value);
static_assert(Answer{}() == 42);
constexpr int converted = Answer{};
std::cout << Answer::value << ' ' << converted << ' '
<< std::boolalpha << Positive{}() << ' '
<< std::false_type{}() << '\n';
}Ergebnis
42 42 true false
Der angezeigte Code und das angegebene Ergebnis wurden in einer isolierten Umgebung mit der im Prüfnachweis für genau diese Version dokumentierten Methode verifiziert.