在boost for_each中运行成员函数的向量

Sam*_*Sam 3 c++ lambda boost stl bind

我尝试学习boost lambda表达式,这是一个无法解决的问题.

我怎样才能在for_each中选择Holder的一个选定成员?

#include <iostream>
#include <string>

#include <boost/assign.hpp> 
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>

using namespace std;
using namespace boost::assign;
using namespace boost::lambda;

class Holder
{
public:
    void vRun1(std::string s){ cout << "vRun1 " << s << endl; }
    void vRun2(std::string s){ cout << "vRun2 " << s << endl; }
    void vRun3(std::string s){ cout << "vRun3 " << s << endl; }
};

// --------------------
std::map< std::string, mem_fun_ref_t<void, Holder> > replacer;


insert(replacer)
        ("buh", std::mem_fun_ref(&Holder::vRun1))
        ("mar", std::mem_fun_ref(&Holder::vRun2))
        ("heu", std::mem_fun_ref(&Holder::vRun3));


Holder hol;
Run Code Online (Sandbox Code Playgroud)

我如何在这里打电话给我注册的功能map<>

for_each(replacer.begin(), replacer.end(), /* bind(_1, hol, it.first) */ );
Run Code Online (Sandbox Code Playgroud)

结果应该是

vRun1 buh
vRun2 mar
vRun3 heu
Run Code Online (Sandbox Code Playgroud)

seh*_*ehe 5

看起来好像你稍微复杂一点.我会这样使用boost::function<>:

请访问http://liveworkspace.org/code/b2c5a38d8c3499eefb6330a839a89d0a

#define BOOST_RESULT_OF_USE_DECLTYPE
#include <iostream>
#include <string>
#include <map>
#include <boost/function.hpp>
#include <boost/foreach.hpp>
#include <boost/phoenix.hpp>
using namespace std;

class Holder {
public:
    void vRun1(std::string s){ cout << "vRun1 " << s << endl; }
    void vRun2(std::string s){ cout << "vRun2 " << s << endl; }
    void vRun3(std::string s){ cout << "vRun3 " << s << endl; }
};

typedef std::map< std::string, boost::function<void(Holder&, std::string)> > Replacer;

int main()
{
    Replacer replacer;
    replacer["a"] = &Holder::vRun1;
    replacer["b"] = &Holder::vRun2;
    replacer["c"] = &Holder::vRun3;

    Holder hol;

    for (Replacer::const_iterator it=replacer.begin(); it != replacer.end(); ++it)
    {
        (it->second)(hol, it->first);
    }
Run Code Online (Sandbox Code Playgroud)

或者:

    std::cout << "Using BOOST_FOREACH:\n";

    BOOST_FOREACH(Replacer::value_type& pair, replacer)
    {
        (pair.second)(hol, pair.first);
    }
Run Code Online (Sandbox Code Playgroud)

甚至:

    std::cout << "Using Boost Phoenix:\n";

    namespace phx = boost::phoenix;
    using namespace phx::arg_names;

    std::for_each(replacer.begin(), replacer.end(),
            phx::bind(
                phx::bind(&Replacer::value_type::second, arg1), 
                phx::ref(hol), 
                phx::bind(&Replacer::value_type::first, arg1)));
}
Run Code Online (Sandbox Code Playgroud)

输出

vRun1 a
vRun2 b
vRun3 c
Using BOOST_FOREACH:
vRun1 a
vRun2 b
vRun3 c
Using Boost Phoenix:
vRun1 a
vRun2 b
vRun3 c
Run Code Online (Sandbox Code Playgroud)