The rationale behind std :: bool_constant

I am wondering what is the point of introducing std::bool_constant and its subsequent use for std::true_type and std::false_type (as well as the comparison structures defined in the <ratio> header, see N4389) in C + +17?

So far I have managed to find documents containing the wording:

Although both documents refer to the “rationale” - https://issues.isocpp.org/show_bug.cgi?id=51 - the feed associated with the commentary basically claims that it is “Based on a discussion in C ++ std-lib *” (presumably referring to a private reflector?), without going into details.

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

+6
source share
1 answer

This is pure syntactic sugar. Often we use, for example, sending tags like this:

 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 will need to use a longer specifier type to indicate the type we need: std::integral_constant<bool, ...> . Since using integral_constant for boolean values ​​pops up especially often, a concise and short way to access specializations is required, and bool_constant does. In fact, bool_constant is nothing more than an alias pattern for the bool specialization integral_constant :

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

The only reason ads for true_type and false_type (and other uses of integral_constant<bool, ..> ) were changed for brevity in standard, even; There was no technical need, since integral_constant<bool, false> and bool_constant<false> denote the same type.

+16
source

Source: https://habr.com/ru/post/988466/


All Articles