繁体   English   中英

带decltype布尔算法的尾随返回类型

[英]Trailing return type with decltype boolean arithmetic

我决定玩一个带有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类型选择的层次结构?

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

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

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

decltype(t, u)的情况下,您的返回类型为bool,因此发生另一次隐式强制转换,强制将2的整数变为布尔值(如果转换回int,则为true或1)。

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

这里的关键点是表达式bool + bool的类型为int ,因为对于bool eans而言,没有operator+才有意义。

考虑到存在一个用于intoperator+ ,并且该标准在§4.5/ 6中指定:

bool类型的prvalue可以转换为int类型的prvalue,false变为零,true变为1。

true的prvalue提升为1false的prvalue提升为0

结果可以很容易地看出:

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

2

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM