C++11 supports a new function syntax:
auto func_name(int x, int y) -> int;
Currently this function would be declared as:
int func_name(int x, int y);
The new style does not seem to be widely adopted yet (say in the gcc stl)
However, should this new style be preferred everywhere in new C++11-programs, or will it only be used when needed?
Personally, I prefer the old style when possible, but a code-base with mixed styles looks pretty ugly.
There are certain cases where you must use a trailing return type. Most notably, a lambda return type, if specified, must be specified via a trailing return type. Also, if your return type utilizes a
decltype
that requires that the argument names are in scope, a trailing return type must be used (however, one can usually usedeclval<T>
to work around this latter issue).The trailing return type does have some other minor advantages. For example, consider a non-inline member function definition using the traditional function syntax:
Member typedefs are not in scope until after the name of the class appears before
::get_integers
, so we have to repeat the class qualification twice. If we use a trailing return type, we don't need to repeat the name of the type:In this example, it's not such a big deal, but if you have long class names or member functions of class templates that are not defined inline, then it can make a big difference in readability.
In his "Fresh Paint" session at C++Now 2012, Alisdair Meredith pointed out that if you use trailing return types consistently, the names of all of your functions line up neatly:
I've used trailing return types everywhere in CxxReflect, so if you're looking for an example of how code looks using them consistently, you can take a look there (e.g, the
type
class).Another advantage is that the trailing-return-type syntax can be more readable when the function returns a pointer to a function. For example, compare
with
However, one can argue that better readability can be achieved simply by introducing a type alias for the function pointer:
In addition to what others said, the trailing return type also allows to use
this
, which is not otherwise allowedIn the second declaration, we used the traditional style. However since
this
is not allowed at that position, the compiler does not implicitly use it. So thea.end()
uses the statically declared type ofa
to determine whatend
overload ofvector<int>
it is going to call, which ends up being the non-const version.See this nice article: http://www.cprogramming.com/c++11/c++11-auto-decltype-return-value-after-function.html Very good example when to use this syntax without decltype in game:
And brilliant explanation also stolen from Alex Allain's article "Because the return value goes at the end of the function, instead of before it, you don't need to add the class scope."
Compare to this possible case when one by accident forget about class scope, and, for bigger disaster, another PersonType is defined in global scope: