Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use decltype to access a dependent-type?

First: my apologies if I am getting the nomenclature wrong!

Basically, I have a not-too-uncommon desire to declare a stack based container, such as:

std::map<CString, size_t> ecounts;

Then I want to iterate over the contents of ecounts a little further down in the function body, but I really don't want to have to typedef a bunch of things, nor retype the above types in order to get the compiler to 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 the declaration of ecounts manually:

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

But, yuck! I'd much rather have a single declaration of what ecounts is, and just use it's value_type somehow. But this seems not to work:

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

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

How might I go about making a sort of One Definition Rule to such code, preferably without having 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 is not the end of the world, obviously, but if I can use decltype, I'd be happier with the resulting reduction in thinking & backtracking to achieve the above...

like image 218
Mordachai Avatar asked Dec 27 '22 11:12

Mordachai


1 Answers

Limitation of VS2010, as the addition you want came into the standard too late for it. It should compile with a conformant compiler. As a workaroung, just use decltype(*ecounts.begin()) e. Or an identity template:

template<class T>
struct identity{ typedef T type; };
// usage: identity<decltype(ecounts)>::type::value_type
like image 50
Xeo Avatar answered Jan 16 '23 11:01

Xeo