Can we access typedef'ed types through an instance?

Interesting,

for(std::map<int, double, std::greater<int> >::iterator it = mymap.begin(); it != mymap.end(); ++it) { //do stuff } 

Why can't I write this as:

 for(mymap::iterator it = mymap.begin(); it != mymap.end(); ++it) { //do stuff } 

Of course, typing a map will make the first code less verbose - but that's not my point. The compiler knows the type mymap , so why not let it allow mymap::iterator ? Is there a reason the iterator not available through the instance?

+8
c ++ types
source share
2 answers

:: is the scope resolution operator that expects a type name or namespace name on the left. It does not accept object names on the left. Solving this is likely to be overly complex in the language.

In fact, if someone allowed something like this, probably this function could be bound to an operator . , since the operator . - the one used with objects on the LHS

 for (mymap.iterator it = mymap.begin(); it != mymap.end(); ++it) 

But it would still unnecessarily complicate things.

In the future, C ++ is standard, something like this will be possible thanks to decltype keyword

 for (decltype(mymap)::iterator it = mymap.begin(); it != mymap.end(); ++it) 

PS According to the Wikipedia article on decltype , its presence in skilled expired was a matter. If I understood correctly, this use was eventually voted.

PPS Also, as @Asha notes in the comments, in the future C ++ you will be able to avoid type naming at all

 for (auto it = mymap.begin(); it != mymap.end(); ++it) 
+12
source share

This iterator is a type that is defined in the map area, and not part of the objects created on the map.

+1
source share

All Articles