Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rationale behind std::bool_constant

Tags:

c++

c++17

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:

  • http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4334.html
  • http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4389.html

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

like image 558
Matt Avatar asked Jun 03 '15 17:06

Matt


1 Answers

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

void foo_impl(std::false_type) { /*Implementation for stuff (and char) */}
void foo_impl(std::true_type ) { /*Implementation for integers but not char*/}

template <typename T>
void foo(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.

like image 92
Columbo Avatar answered Sep 28 '22 02:09

Columbo