In one system header file, I see the expression like this:
auto create_task(_Ty _Param) -> task<typename details::_TaskTypeFromParam<_Ty>::_Type>
{…}
I don’t know what "->" means, it isn’t pointer expression or lambda expression, can anyone help me?
It’s the new function declaration syntax from C++11, and it’s called the “trailing return type”. At the end of a function declaration,
->means that the following is the return type of the function. It can only be used when theautokeyword is used instead of an actual return type where you would normally expect it.For instance, these two declarations are compatible:
Depending on your tastes, you may find it prettier than the old declaration syntax, especially when the return type is extremely long/complex:
But sometimes it can be necessary with templates, when the return type of the function could vary with the arguments.
Say you want a templated function to add variables:
That’s great, but you’ll only be able to add variables of the same type. Suppose you would like to be able to add variables of any type (like
add((int)1, (double)2)).EDIT: note that in C++14 and onwards, it’s legal to write
auto add(const T& x, const U& y), without a trailing return type, for function definitions (in other words, when you define the body of your function).The problem is that you can’t tell in advance what the result type of
x + ywill be. As templates stand, they could even be non-integral types. (Wouldn’t you like to be able to doadd(std::string("x"), "y")?)Decltype, along with the new function declaration syntax, lets you solve this problem.Decltype“returns” the type of an expression. Since you needxandyto have been declared fordecltype(x + y)to work, you need the new syntax.