Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using std::get<>() in std::for_each

I have a map which is being iterated over in a std::for_each loop. I am using a nested bind and simple helper functions to get to the element of the pair I require. This has to be usable from pre c++11 code.

typedef std::map<int, Foo> MapType;

std::for_each( 
    testMap.begin() , 
    testMap.end() , 
    std::bind( 
      &Foo::myIncredibleFunction ,  
      std::bind( 
          &ValueExtractor< MapType::key_type , MapType::mapped_type >::getValue, 
          std::placeholders::_1 )));

This works fine (although I'm sure could be refined)

I am also going to be migrating the current code base from the current level to C++11 and so I am looking at whether I can use new features of the language to improve the code (readability, efficiency). For example I have tried the following (Unsuccessfully - see template error below)

std::for_each( 
    testMap.begin() , 
    testMap.end() , 
    std::bind( 
        &Foo::myIncredibleFunction ,  
        std::get<1>(  std::placeholders::_1 )));

error

    1>d:\projects\test_bind\test_bind\test_bind.cpp(48): error C2780:
    std::bind ...<Snip>...
    : expects 6 arguments - 2 provided

also intellisense has the following:

IntelliSense: no instance of overloaded function "std::get" matches the argument list
argument types are: (std::_Ph<1>)   

I have tried various combinations of usages of std:get<1>() to try to replace my inner bind with no success. I suspect that I am failing to understand this properly but it feels like I should be able to do what I want. Is there a way to do this using the std::get call and without a helper function/functor?

Edit: I think KennyTM has come up with my answer with regard to what I actually do in the code, it's so much better than my approach. I'm still interested in whether std::get<> could be used above or why not.

like image 933
Caribou Avatar asked Dec 13 '25 23:12

Caribou


1 Answers

Since you're using C++11 already, why not use a range-based for loop (which is supported in VS 2012)?

for (auto&& item : testMap) {
    item.second.myIncredibleFunction();
}
like image 77
kennytm Avatar answered Dec 16 '25 14:12

kennytm