C++1y Automatic Type Deduction
The addition, err, redefinition of the auto keyword in C++11 was a great move to reduce code verbosity during the definition of local variables:
In addition to this convenient usage, employing auto in conjunction with the new (and initially weird) function-trailing-return-type syntax is useful for defining function templates that manipulate multiple parameterized types (see the third entry in the list of function definitions below).
In the upcoming C++14 standard, auto will also become useful for defining normal, run-of-the-mill, non-template functions. As the fourth entry below illustrates, we’ll be able to use auto in function definitions without having to use the funky function-trailing-return-type syntax (see the useless, but valid, second entry in the list).
For a more in depth treatment of C++11’s automatic type deduction capability, check out Herb Sutter’s masterful post on the new AAA (Almost Always Auto) idiom.
C++14 adds even more auto support than that:
auto add = [](auto x, auto y) {return x + y;}
Thanks Chris.
Trailing return type without templates is also useful for out-of-line member function definitions where the return type is a member of the class type:
struct foo {
struct blah {};
blah get_blah();
};
//compare:
foo::blah foo::get_blah() { … }
auto foo::get_blah() -> blah { … }
The second one doesn’t need to scope `blah` to `foo`, since the trailing return type is already within that scope. Not a major difference in legibility here, granted, but I find it useful for more verbose types.
Nice! That’s why I love C++. Just when you think you’ve got a feature down, you learn new, unanticipated uses for it. Thanks.