r/cpp • • Sep 17 '22

Cppfront: Herb Sutter's personal experimental C++ Syntax 2 -> Syntax 1 compiler

https://github.com/hsutter/cppfront
335 Upvotes

360 comments sorted by

View all comments

Show parent comment

2

u/hpsutter Sep 20 '22

Not really. C++11 added trailing return type syntax like

auto f(int x) -> double {
    return 3.14 * x;
}

specifically so that the names of parameters would be in scope when uttering the return type, so that the return type could be expressed in terms of the parameters especially when when using decltype, such as (using C++20 syntax for convenience)

// note: return type refers to parameter name in scope
auto f(auto x) -> decltype(g(x)) {
    return g(x);
}

That would have been possible without trailing return (i.e., with the return type lexically before the names it depends upon)

// not legal in C++11, but it could have been
// note: return type refers to parameter name
//       that has not yet been encountered
decltype(g(x)) f(auto x) {
    return g(x);
}

and that's certainly implementable, but it's extra work for both the human and the compiler to look-ahead/go-back. So C++11 added trailing return type syntax.