Possible Duplicate:
What is “->” after function declaration?
I’ve just come across the following examples of C++ functions using the new auto keyword, and I was hoping someone could help me understand what the syntax means.
template <class T, class U>
auto add(T t, U u) -> decltype(t + u);
auto f = [](int a, int b) -> int {
return a*b;
};
Specifically, I’m confused about the user of -> in the function signature and I would expect these to be written in the as
template <class T, class U>
auto add(T t, U u)
{
decltype(t + u);
}
auto f = [](int a, int b){
return a*b;
};
What’s the -> operator doing in there, and where can I learn more about this syntax?
That’s a trailing return type. Instead of:
you can equivalently write:
If the return type depends on the function parameter types, then you need to use this form; the parameters aren’t available until after they’ve been declared:
Also, if you want to specify the return type of a lambda, then you must use this form; although, as you point out, in many cases (including this one) you don’t need to specify that at all.