【问题标题】:Trailing return type with decltype boolean arithmetic带有 decltype 布尔运算的尾随返回类型
【发布时间】:2014-01-15 11:04:16
【问题描述】:

我决定尝试使用如下所示的 delctype 的尾随返回类型:

template<typename T, typename U>
auto Add(T t, U u) ->decltype(t,u)
{
    return t + u;
}

如果我发送整数或双精度数,则效果很好,例如

Add(10,11); //21
Add(5.35,2.22); //7.57

但后来我问自己这是否适用于布尔算术?

Add(true,true); // = 1 + 1 = 1;
Add(true, false); // = 1 + 0 = 1    
Add(false, false); // = 0 + 0 = 0;

在这种情况下它运行良好,但后来我决定尝试以下方法:

->decltype(t + u)

这给了我结果:

Add(true,true); // = 1 + 1 = 2;
Add(true, false); // = 1 + 0 = 1
Add(false, false); // = 0 + 0 = 0;

我假设 decltype(t+u) 将返回类型推断为 int 而不是 bool?为什么是这样? decltype 会选择类型的层次结构吗?

【问题讨论】:

  • 因为自动提升为整数的 bool 之和的 decltype 是整数?
  • @Jefffrey 抱歉已修复 :)
  • @dionadar 是的,这就是我的想法,真的只是一个小问题。
  • 实际上,decltype(t,u)decltype((t,u))decltype((u))bool&amp; 并且 Add 的实例化应该失败,因为 return 尝试将临时绑定到非 const 左值参考。见here (freshly asked)there

标签: c++ c++11


【解决方案1】:

简答:因为表达式的类型是int 而不是bool

长答案:通过调用Add(true, true),您的模板类型参数TU 被推断为布尔值。因此,表达式t, u 的类型为bool。请注意,此表达式中的逗号是逗号运算符,正如@ccom 所指出的那样。

由于您不能在算术上添加布尔值(符号 + 有时在逻辑中用于表示 or 运算符,在 c++ 中是 |),c++ 会自动将两个布尔值提升为整数,然后执行加法。

decltype(t, u) 的情况下,您的返回类型是 bool,因此会发生另一个隐式转换,迫使您的整数 2 变为布尔值(true 或 1,当转换回 int 时)

decltype(t + u) 的情况下,返回类型是表达式的类型 (int),因此最终的转换根本没有完成 - 给你 2。

【讨论】:

    【解决方案2】:

    这里的关键点是表达式bool + boolint 类型,因为没有operator+booleans 有意义。

    考虑到ints 的operator+ 存在,并且标准在§4.5/6 中指定:

    bool 类型的纯右值可以转换为 int 类型的纯右值,false 变为 0,true 变为 1。

    true 的纯右值提升为1false 的纯右值提升为0

    这可以通过以下结果很容易看出:

    std::cout << (true + true);
    

    is 2.

    在您的第一种情况下,decltype(t, u) 显然是 bool,因为 tu 都是 bool。 在第二种情况下,由于上述原因,decltype(t + u)int

    【讨论】:

      猜你喜欢
      • 2011-11-07
      • 2017-08-02
      • 2017-10-08
      • 2019-01-26
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2011-04-14
      • 1970-01-01
      相关资源
      最近更新 更多