自C ++ 14起合法使用尾随返回类型语法 [英] Legitimate uses of the trailing return type syntax as of C++14
问题描述
实际上是否有理由再使用以下语法:
Is there actually any reason to use the following syntax anymore :
template<typename T>
auto access(T& t, int i)
-> decltype(t[i])
{
return t[i];
}
现在我们可以使用了:
template<typename T>
decltype(auto) access(T& t, int i)
{
return t[i];
}
尾随返回类型语法现在看起来有点多余吗?
The trailing return type syntax now seems a little redundant?
推荐答案
推论的返回类型不是SFINAE友好的.如果t[i]
无效,则此过载将简单地退出过载设置:
Deduced return types are not SFINAE friendly. This overload will simply drop out of the overload set if t[i]
is invalid:
template<typename T>
auto access(T& t, int i)
-> decltype(t[i])
{
return t[i];
}
此过载不会导致严重错误:
Whereas this overload will not, leading to a hard error:
template<typename T>
decltype(auto) access(T& t, int i)
{
return t[i];
}
此外,您可能会遇到推论的返回类型冲突的问题.考虑是否要返回std::optional<T>
.由于std::nullopt_t
与std::optional<T>
的类型不同,因此以下代码无法编译:
Also, you can run into issues with conflicting deduced return types. Consider if I wanted to return a std::optional<T>
. The following code doesn't compile since std::nullopt_t
is not the same type as std::optional<T>
:
#include <optional> // C++17 standard library feature
template <typename T>
auto foo(T const& val)
{
if (val.is_invalid()) return std::nullopt;
return val.some_function_returning_an_optional();
}
通过跟踪返回类型,您可以准确指定要返回的表达式的类型:
Trailing return types let you specify exactly which expressions' type to return:
template <typename T>
auto foo(T const& val)
-> decltype(val.some_function_returning_an_optional())
{
if (val.is_invalid()) return std::nullopt;
return val.some_function_returning_an_optional();
}
您可以使用前导返回类型,但是这需要使用std::declval
,这使得它很难理解:
You could use a leading return type, but it would require the use of std::declval
, which makes it harder to understand:
template <typename T>
decltype(std::declval<T const&>().some_function_returning_an_optional())
foo(T const& val)
{
if (val.is_invalid()) return std::nullopt;
return val.some_function_returning_an_optional();
}
这篇关于自C ++ 14起合法使用尾随返回类型语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!