Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 991
geza Avatar asked Feb 04 '23 17:02

geza


2 Answers

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.

like image 169
HolyBlackCat Avatar answered Feb 06 '23 11:02

HolyBlackCat


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

like image 22
user1810087 Avatar answered Feb 06 '23 12:02

user1810087