Matt
Matt

Reputation: 628

Rationale behind std::bool_constant

I'm wondering, what is the rationale behind introducing std::bool_constant and its subsequent use for std::true_type and std::false_type (as well as the comparison structs defined in header <ratio>, cf. N4389) in C++17?

Thus far I've only been able to locate the papers containing the wording:

While both paper refer to a "rationale" -- https://issues.isocpp.org/show_bug.cgi?id=51 -- the linked-to comment feed mostly states that this is "Based on the discussion on c++std-lib*" (presumably referring to the private reflector?) without going into further details.

Here is the the documentation: http://en.cppreference.com/w/cpp/types/integral_constant

Upvotes: 11

Views: 4980

Answers (1)

Columbo
Columbo

Reputation: 60999

It's pure syntactic sugar. Often, we use e.g. tag-dispatching like so:

template <typename T>
void foo_impl(T t, std::false_type) { /*Implementation for stuff (and char) */}
template <typename T>
void foo_impl(T t, std::true_type ) { /*Implementation for integers but not char*/}

template <typename T>
void foo(T t) {
    foo_impl(t, std::bool_constant<std::is_integral<T>{} && !std::is_same<char, T>{}>());
}

Without bool_constant, we'd have to use a longer type-specifier to designate the desired type: std::integral_constant<bool, ...>. Since the usage of integral_constant for boolean values pops up especially often, a concise and short way of adressing the specializations was asked for, and bool_constant provides that.
In fact, bool_constant is nothing more than an alias template for bool-specializations of integral_constant:

template <bool B>
using bool_constant = integral_constant<bool, B>;

The only reason the declarations for true_type and false_type (and other uses of integral_constant<bool, ..>) were altered is for brevity in the standard, even; There was no technical need, as integral_constant<bool, false> and bool_constant<false> designate the exact same type.

Upvotes: 20

Related Questions