使用的好处是什么
template <typename L, typename R>
auto getsum(L l, R r) -> decltype(l + r) {return l + r;}
结束
template <typename L, typename R>
auto getsum(L l, R r) {return l + r;}
不是在模板实例化期间自动编译成适当的类型吗?
一个明显的优点是代码更短。
但也有不足之处:除了只能从C++14中自动推送返回类型外,还存在不能推送返回类型的情况。
假设函数的复杂度略微增加:
template <typename L, typename R>
auto getsum(L l, R r) {
if (l < 0)
return 0;
return l + r;
}
现在以下内容将无法编译:
int main() {
auto s = getsum(1L, 2); // error: inconsistent deduction for auto return type: 'int' and then 'long int'
}
我们通过显式指定返回类型(例如,使用尾随返回类型语法)来解决这个问题:
auto getsum(L l, R r) -> decltype(l + r) {
if (l < 0)
return 0;
return l + r;
}
int main() {
auto s = getsum(1L, 2); // OK
}
使用“尾随返回类型语法”有什么好处?
一个可能的优点:尾随返回类型是SFINAE友好的。
只有当l
和r
之间存在加号运算符时,才启用具有尾随返回类型(->decltype(l+r)
)getSum()
函数。
如果使用两个不支持sum的参数调用它(例如,两个std::vector
),则会得到一个不是错误的替换失败(SFINAE)。
因此可以调用另一个getSum()
函数。
下面是一个完整的编译示例,其中从getsum(a,b)
调用“Do something difference”版本
#include <vector>
template <typename ... Ts>
auto getsum (Ts...)
{ /* do something different */ }
template <typename L, typename R>
auto getsum (L l, R r) -> decltype( l + r )
{ return l + r; }
int main ()
{
std::vector<int> a, b;
getsum(a, b);
}
但是如果移除尾随返回类型
template <typename L, typename R>
auto getsum (L l, R r) // <<--- no more tailing return type!!!
{ return l + r; }
代码不再编译,因为您没有替换失败,而是硬错误。
自C++14以来,第二个版本只是第一个版本的一个更简单的版本。 在C++14之前,您可以用auto
对齐函数名(因此这是关于codestyle的)。