Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we access typedef'ed types via an instance?

Tags:

c++

types

I wondered,

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

Why am I not able to write this as:

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

Of course, typedeffing the map would make the first code less verbose - but that is not my point. The compiler knows the type of mymap, so why not let it resolve mymap::iterator? Is there a reason why iterator is not accessible via the instance?

like image 855
nakiya Avatar asked Mar 10 '11 07:03

nakiya


2 Answers

:: is a scope resolution operator that expects type name or namespace name on the left-hand side. It doesn't accept object names on the left-hand side. Allowing this would probably overcomplicate a lot of things in the language.

In fact, if one would to allow something like this, one'd probably attach this functionality to . operator, since . operator is the one used with objects on the LHS

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

But this still would unnecessarily overcomplicate things anyway.

In the future C++ standard something like that will become possible through decltype keyword

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

P.S. According to Wikipedia article on decltype, its availability in qualified-ids was a matter of debate. If I understood it correctly, this usage was eventually voted in.

P.P.S. Also, as @Asha noted in comments, in the future C++ you'll be able to avoid naming the type at all

for (auto it = mymap.begin(); it != mymap.end(); ++it) 
like image 177
AnT Avatar answered Sep 19 '22 13:09

AnT


That iterator is a type which is defined in the scope of map and not part of objects created from map.

like image 28
Shamim Hafiz - MSFT Avatar answered Sep 17 '22 13:09

Shamim Hafiz - MSFT