Boost.Bind to access std::map elements in std::for_each

后端 未结 4 866
后悔当初
后悔当初 2020-12-16 03:49

I\'ve got a map that stores a simple struct with a key. The struct has two member functions, one is const the other not. I\'ve managed calling the const function using std::

4条回答
  •  再見小時候
    2020-12-16 04:30

    If you find yourself having to do this a lot I recommend you use the Boost.RangeEx library:

    #include 
    #include 
    #include 
    #include 
    
    struct MyStruct {
      void someConstFunction() const;
      void someFunction();
    };
    
    typedef std::map MyMap;
    MyMap theMap;
    
    int main()
    {
        //call the const member function
        boost::for_each(theMap | boost::adaptors::map_values,
                        boost::mem_fn(&MyStruct::someConstFunction));
    
        //call the non-const member function
        boost::for_each(theMap | boost::adaptors::map_values,
                        boost::mem_fn(&MyStruct::someFunction));
    }
    

    It's been accepted into Boost but it doesn't come with the official distribution yet. Until it does you can download it from the Boost Vault (download link to zip file).

提交回复
热议问题