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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…