Why does C++ not allow multiple types in one auto statement?

Posted by Walter on Stack Overflow See other posts from Stack Overflow or by Walter
Published on 2013-10-31T12:50:46Z Indexed on 2013/10/31 21:55 UTC
Read the original article Hit count: 276

Filed under:
|
|
|

The 2011 C++ standard introduced the new keyword auto, which can be used for defining variables instead of a type, i.e.

auto p=make_pair(1,2.5);                   // pair<int,double>
auto i=std::begin(c), end=std::end(c);     // decltype(std::begin(c))

In the second line, i and end are of the same type, referred to as auto. The standard does not allow

auto i=std::begin(container), e=std::end(container), x=*i;

when x would be of different type. My question: why does the standard not allow this last line? It could be allowed by interpreting auto not as representing some to-be-decuded type, but as indicating that the type of any variable declared auto shall be deduced from its assigned value. Is there any good reason for the C++11 standard to not follow this approach?

There is actually a use case for this, namely in the initialisation statement of for loops:

for(auto i=std::begin(c), end=std::end(c), x=*i;  i!=end;  ++i, x+=*i)
{ ... }

when the scope of the variables i, end, and x is limited to the for loop. AFAIK, this cannot be achieved in C++ unless those variables have a common type. Is this correct? (ugly tricks of putting all types inside a struct excluded)

There may also be use cases in some variadic template applications.

© Stack Overflow or respective owner

Related posts about c++

Related posts about c++11