std :: bool_constant背后的基本原理

Mat*_*att 5 c++ c++17

我想知道,在C++ 17中引入std::bool_constant及其后续使用std::true_typestd::false_type(以及在头文件中定义的比较结构<ratio>,参见N4389)背后的原理是什么?

到目前为止,我只能找到包含措辞的文件:

虽然两篇论文都提到了"理由" - https://issues.isocpp.org/show_bug.cgi?id=51 - 链接评论提要主要表明这是"基于对c ++的讨论std-lib*"(大概是指私人反射器?)而没有进一步的细节.

以下是文档:http: //en.cppreference.com/w/cpp/types/integral_constant

Col*_*mbo 16

这是纯粹的语法糖.通常,我们使用例如tag-dispatching,如下所示:

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>{}>());
}
Run Code Online (Sandbox Code Playgroud)

如果没有bool_constant,我们必须使用更长的类型说明符来指定所需的类型:std::integral_constant<bool, ...>.由于integral_constant布尔值的使用特别经常弹出,因此要求bool_constant提供简明扼要的专门化方法,并提供了这一点.
实际上,bool_constant它只不过是bool-specializations的别名模板integral_constant:

template <bool B>
using bool_constant = integral_constant<bool, B>;
Run Code Online (Sandbox Code Playgroud)

改变声明true_typefalse_type(和其他用途integral_constant<bool, ..>)的唯一原因是标准的简洁,甚至; 没有技术需要,integral_constant<bool, false>并且bool_constant<false>指定完全相同的类型.