What is the meaning of auto main()->int?

It is called trailing-return-type. It is particularly useful in generic codes using templates where the return type of depends on the expression involving some other template arguments. It is also used in lambda.

Here is an example:

template<typename T, typename U>
auto add(T t, U u) -> decltype(t+u)
{
   return t + u;
}

Here the return type depends on the expression t+u. So whatever the type of the expression, is also the return-type of the function, which is indicated by decltype(t+u).


C++11 introduced a notation for trailing return types: If a function declaration is introduced with auto, the return type will be specified after the parameters and a -> sequence. That is, all that does is to declare main() to return int.

The significance of trailing return types is primarily for function template where it is now possible to use parameters to the function together with decltype() to determine the return type. For example:

template <typename M, typename N>
auto multiply(M const& m, N const& n) -> decltype(m * n);

This declares the function multiply() to return the type produced by m * n. Putting the use of decltype() in front of multiply() would be invalid because m and n are not, yet, declared.

Although it is primarily useful for function template, the same notation can also be used for other function. With C++14 the trailing return type can even be omitted when the function is introduced with auto under some conditions.


This is a uniform function declaration syntax, trailing return type, introduced in C++11.

You can't use any other syntax for lamdas, and it's also very convenient for function templates where the result type depends on arguments.

If you want to select one single syntax (and I think that's a good idea), then you don't have any choice: the old syntax can't be used for lambdas.

Reason for doing that include:

  • Well, a single syntax.

  • Function name always at the same place visually, supports fast scanning of code.

  • Ditto for the result type, easy visual recognition (plus, you don't have to qualify it when it's a type defined in a member function's class).

Reasons against include some added verbosity, use of old compilers that don't understand this syntax, that anything new can feel scary and uncomfortable and just odd.

Tags:

C++

C++11