How can I use decltype to access the dependent type?

First: my apologies if I am mistaken in the nomenclature!

Basically, I have a not-so-unusual desire to declare a container based on a stack, for example:

std::map<CString, size_t> ecounts; 

Then I want to repeat the contents of ecounts contents a little further in the function body, but I really do not want typedef to have a bunch of things, and do not retype the above types to make the compiler work with what I have ...

 std::foreach(ecounts.begin(), ecounts.end(), [&] (>>>here is the problem<<< e) { ... whatever I want to do with e ... } 

Of course, I can either use typedefs or my knowledge of declaring ecounts manually:

 std::foreach(ecounts.begin(), ecounts.end(), [&] (std::pair<CString,size_t> e) ... 

But yes! I would prefer one declaration of what ecounts is and just use its value_type somehow. But this does not seem to work:

 std::foreach(ecounts.begin(), ecounts.end(), [&] (decltype(ecounts)::value_type e) ... 

Is this just a limitation of my compiler (vs2010), or is it a limitation of C ++?

How can I make such a definition rule for such code, preferably without the need to use typedefs to achieve it (i.e. I can do the following):

 typedef std::map<CString, size_t> maptype; typedef maptype::value_type valuetype; maptype ecounts; ... std::foreach(ecounts.begin(), ecounts.end(), [&] (valuetype e) ... 

This, of course, is not the end of the world, but if I could use decltype, I would be happier with the result of reduced thinking and going back to achieve the above ...

+4
source share
2 answers

A limitation of VS2010, because the add you want went into the standard too late for it. It must be compiled using the appropriate compiler. As a worker, use only decltype(*ecounts.begin()) e . Or identification template:

 template<class T> struct identity{ typedef T type; }; // usage: identity<decltype(ecounts)>::type::value_type 
+8
source

If all you want to do is just iterate over the container, just use the new style for the loop:

 for (auto e: ecounts) { // whatever you want to do with e } 

Or, if you want to change the elements on the map:

 for (auto& e: ecounts) { // ... } 
+2
source

Source: https://habr.com/ru/post/1381812/


All Articles