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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With