在下面的情境中
template <class T>
? f(T&& a, T&& b)
{
return a > b ? a : b;
}
最佳的返回类型应该是什么? 我目前的想法是:
使用r值引用进行返回,并完美转发函数参数:
template <class T>
decltype(auto) f(T&& a, T&& b)
{
return a > b ? forward<T>(a) : forward<T>(b);
}
移动构造返回值:
template <class T>
auto f(T&& a, T&& b)
{
return a > b ? forward<T>(a) : forward<T>(b);
}
尝试找到一种方法来启用(N)RVO(即使我认为,由于我想要使用函数参数,这是不可能的)
这些解决方案有问题吗?有更好的解决方法吗?最佳实践是什么?
int
,U 是double
。那么三元运算符的类型将是什么?我会让你自己思考,你应该能理解我的意思。 - Lorah Attkinschar a,b; decltype(a+b) c; std::cout << sizeof(c);
这样的东西会打印出 4。 - PeterTtemplate <class T, class U> decltype(auto) f(T&& a, U&& b)
这样写没问题;或者你可以让它支持 sfinae,template <class T, class U> auto f(T&& a, U&& b) -> decltype(a > b ? forward<T>(a) : forward<U>(b))
。在这两种情况下,编译器会根据条件运算符的操作数确定一个通用类型,来计算适当的返回类型(如果有的话)。我认为你不可能获得比这更多的东西了。 - Piotr Skotnicki