I found such code:
template <typename T, typename T1> auto compose(T a, T1 b) -> decltype(a + b) {
return a+b;
}
I figured with all details, that were new to me, but one.
Tell me please, where can I read about, what does the arrow operator (->
) mean in function heading?
I guess purely logically, that ->
operator determines a type, that will be gotten by auto
, but I want to get this straight, but can't find information.
In plain english it tells that the return type is the inferred type of the sum of
a
andb
.In C++11, there are two syntaxes for function declaration:
return-type identifier
(
argument-declarations...)
and
auto
identifier(
argument-declarations...)
->
return_typeThey are equivalent. Now when they are equivalent, why do you ever want to use the latter? Well, C++11 introduced this cool
decltype
thing that lets you describe type of an expression. So you might want to derive the return type from the argument types. So you try:and the compiler will tell you that it does not know what
a
andb
are in thedecltype
argument. That is because they are only declared by the argument list.You could easily work around the problem by using
declval
and the template parameters that are already declared. Like:except it's getting really verbose now. So the alternate declaration syntax was proposed and implemented and now you can write
and it's less verbose and the scoping rules didn't need to change.
C++14 update: C++14 also permits just
auto
identifier(
argument-declarations...)
as long as the function is fully defined before use and all
return
statements deduce to the same type. The->
syntax remains useful for public functions (declared in the header) if you want to hide the body in the source file. Somewhat obviously that can't be done with templates, but there are some concrete types (usually derived via template metaprogramming) that are hard to write otherwise.