【问题标题】:Rationale behind std::bool_constantstd::bool_constant 背后的基本原理
【发布时间】:2015-08-18 01:15:27
【问题描述】:

我想知道,在 C+ 中引入 std::bool_constant 及其随后用于 std::true_type 和 std::false_type(以及在标头 <ratio> 中定义的比较结构,参见 N4389)背后的基本原理是什么+17?

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

虽然两篇论文都提到了“基本原理”——https://issues.isocpp.org/show_bug.cgi?id=51——但链接到的评论提要大多指出这是“基于对 c++std-lib* 的讨论”(大概是指私人反射器?),不再赘述。

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

【问题讨论】:

  • 我也是第一个想法。阅读有关 SFINAE 的信息,这可能很有用。
  • @LightnessRacesinOrbit SFINAE 和它有什么关系?
  • @MarcAndreson:我没能用“SFINAE”代替更好的主意,但这不是错误;)
  • @LightnessRacesinOrbit 实际上,您能想出任何合理的例子,说明bool_constant 应该与SFINAE 结合使用吗?我不能,我的头顶。
  • Boost.MPL 在某种意义上是现代元编程的先驱,它伴随着mpl::bool_<>(以及mpl::int_ 等),因此该技术有先例。

标签: c++ c++17


【解决方案1】:

它是纯粹的语法糖。通常,我们使用例如像这样进行标签调度:

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>{}>());
}

如果没有bool_constant,我们将不得不使用更长的类型说明符来指定所需的类型:std::integral_constant&lt;bool, ...&gt;。由于布尔值使用integral_constant 的用法特别频繁,因此需要一种简洁而简短的处理专业化的方法,而bool_constant 提供了这一点。
其实bool_constant只不过是bool的别名模板-integral_constant的专业化:

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

true_type 和 false_type(以及integral_constant&lt;bool, ..&gt; 的其他用途)的声明被更改的唯一原因是为了标准的简洁,甚至;没有技术需求,因为integral_constant&lt;bool, false&gt; 和bool_constant&lt;false&gt; 指定完全相同的类型。

【讨论】:

  • 每当我重复使用std::integral_constant 时,我最终都会写出类似的别名;这是一个论据。 OTOH,我使用bool_t 而不是那么长的东西。简洁才是重点。
  • 感谢您的回答!而且,是的,我已经在使用std::integral_constant,所以这个问题有一个隐含的“而不是像以前那样只使用std::integral_constant&lt;bool, B&gt;”部分,你也回答了:语法糖和简洁是有道理的:-)
猜你喜欢
  • 2023-04-08
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-19
  • 1970-01-01
  • 2014-06-26
相关资源
最近更新 更多