What is the meaning of auto when using C++ trailing return type?
Instead of usual
void foo (void ) {
cout << "Meaning of life: " << 42 << endl;
}
C++11
allows is an alternative, using the Trailing Return
auto bar (void) -> void {
cout << "More meaning: " << 43 << endl;
}
In the latter - what is auto
designed to represent?
Another example, consider function
auto func (int i) -> int (*)[10] {
}
Same question, what is the meaning of auto
in this example?
Solution 1:
In general, the new keyword auto
in C++11 indicates that the type of the expression (in this case the return type of a function) should be inferred from the result of the expression, in this case, what occurs after the ->
.
Without it, the function would have no type (thus not being a function), and the compiler would end up confused.
Solution 2:
Consider the code:
template<typename T1, typename T2>
Tx Add(T1 t1, T2 t2)
{
return t1+t2;
}
Here the return type depends on expression t1+t2
, which in turn depends on how Add
is called. If you call it as:
Add(1, 1.4);
T1
would be int
, and T2
would be double
. The resulting type is now double
(int+double). And hence Tx
should (must) be specified using auto
and ->
template<typename T1, typename T2>
auto Add(T1 t1, T2 t2) -> decltype(t1+t2)
{
return t1+t2;
}
You can read about it in my article.
Solution 3:
I think the answer is relatively straightforward, and not covered in other answers here.
Basically, without the auto
, there are ambiguities, so The Committee decided "you need auto
here to avoid those ambiguities".
class A {
T B;
};
class B;
A* f();
f()->B;
Now, what does f()->B
mean? Is it a function with no parameters that returns a B
(with trailing return type syntax), or is it a function call to A* f()
?
If we didn't have the auto
required at the start of the trailing return type syntax, we wouldn't be able to tell. With the auto
, it's clear that this is a function call.
So, to avoid the unclearness here, we simply require auto
at the start of any function declaration that uses a trailing return type.