With the introduction of auto
return type in C++14, is there any real situation that trailing return type is required or it's completely obsolete in C++14 and 17?
Consider...
auto f(int x)
{
if (x == 2)
return 3;
return 2.1;
}
...this has an ambiguous return type - int
or double
. An explicit return type - whether prefixed or trailing - can disambiguate it and casts the return
argument to the return type.
Trailing return types specifically are also useful if you want to use decltype
, sizeof
etc on some arguments:
auto f(int x) -> decltype(g(x))
{
if (x == 2)
return g(x);
return 2;
}