Example where trailing return type must be used, because the problem cannot be solved the old way

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

Tags:

C++