Is there any case, where we must use trailing return type, because the problem cannot be phrased in the old way?
auto fn() -> int;
can be easily transformed to the old way: int fn();
.
I wonder, is there an example, where this transformation is not possible. The most straighforward example, when we refer to function parameters in the return type, seems to be solvable by using declval
.
Note: don't consider lambdas here, where we must use trailing return type.
In a trailing return type, you're allowed to apply decltype
to this
(see this question).
With the old syntax, you'd have to spell the class name manually... which you can't do if the class is unnamed!
(Or if the member function is generated with a macro, so the class name isn't known.)
struct
{
auto foo() -> decltype(this)
{
return this;
}
/*
decltype(this) foo() // error: invalid use of 'this' at top level
{
return this;
}
*/
} x;
I admit that this is a slightly unrealistic example, and you can easily work around it by naming the class, but I couldn't think of anything else.
One bizzare example I can think of, which needs some prerequisites.
Consider a function which cannot use auto return type deduction (e.g. it has multiple return values which cannot be deduced to the same type) and uses generic function from C++ concepts. Then you don't have a type to use for std::declval
and auto deduction won't work:
auto foo(auto x)
// -> decltype(x) // comment this out to fix
{
if(x > 0) return x;
return -1; // requires int to be implicite castable to type of x
}
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With