简体   繁体   中英

boost::function and multiple argument member-function

I have the following definition of a boost::function object:

typedef boost::function<std::string (std::string, std::string)> concat;

I am passing this function as a struct constructor argument:

struct add_node_value_visitor : boost::static_visitor<>
{
    typedef boost::function<std::string (std::string, std::string)> concat;
    add_node_value_visitor(concat _func, std::string key) : _func_concat(_func), _key(key) {}

    template <typename T>
    void operator() ( const T& value) const
    {
        std::string result = _func_concat(boost::lexical_cast<std::string, T>(value), _key);
    }

    std::string _key;
    concat _func_concat;
};

Now I need to pass the struct add_node_value_visitor to the following function, however the boost::function<T> does not accept the 2 arg member function, in the documentation it says I should use boost::bind, but I am however not sure how I'd do that, seeing I also have to satisfy my boost::apply_visitor function.

boost::apply_visitor( add_node_value_visitor( &Decomposer::ConcatValues, key), var); // ConcatValues takes 2 args, var = boost::variant


std::string ConcatValues(std::string str, std::string key);

Any ideas anybody?

没有看到ConcatValue的声明就很难精确,但是您想要这样的东西:

boost::bind(&Decomposer::ConcatValues, some_decomposer_instance, _1, _2)

您需要提供Decomposer对象的实例,如下所示:

boost::apply_visitor( add_node_value_visitor( boost::bind( &Decomposer::ConcatValues, yourDecomposer, _1, _2 ), key), var);

The answer depends on what ConcatValues really is. I'm guessing that it is actually a non-static member function of a Decomposer class, and that as such it doesn't actually expect two but three parameters : two strings and the Decomposer instance on which it is invoked ( this ).

Boost.Bind is indeed a solution as it will help you bind the first argument of the member function to a Decomposer instance, and forward the two std::string passed :

Decomposer decomposer;
boost::apply_visitor(
   add_node_value_visitor(boost::bind(&Decomposer::ConcatValues, &decomposer, _1, _2), var
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM