Possible to simplify this expression?

c++, c++11, stl

Solution

I recomend `typedef`ing complex templates like the assoc containers, for this reason so you could do something like:

typedef std::unordered_map<KeyType, std::shared_ptr<ValueType>> map_type;

map_type myMap;

//do with map

std::for_each(myMap.begin(), myMap.end(), 
    [](typename map_type::value_type& pair){
        pair.second->someMethod(); 
});

or without the typedef

std::for_each(myMap.begin(), myMap.end(), 
    [](typename decltype(myMap)::value_type& pair){
        pair.second->someMethod(); 
});

decltype gets the type of an object, you need to use the typename defined in a templated class, to do this you use the `typename` keyword. This is necessary in case a template specialisation doesn't have that typedef.

Problem

Lets say I have a class with a member variable: ``` std::unordered_map<KeyType, std::shared_ptr<ValueType>> myMap ``` and in a member function I want to do the following: ``` std::for_each(myMap.begin(), myMap.end(), [](std::pair<const KeyType, std::shared_ptr<ValueType>>& pair){pair.second->someMethod(); }); ``` Is there anyway to shorten the lambda expression? I thought I could do this but it was not valid syntax: ``` std::for_each(myMap.begin(), myMap.end(), [](decltype(myMap::valueType)& pair){pair.second->someMethod(); }); ```

Original source

Related problems