Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::static_visitor with multiple arguments

typedef boost::variant<int, double> Type;
class Append: public boost::static_visitor<>
{
public:
    void operator()(int)
    {}

    void operator()(double)
    {}

};

Type type(1.2);
Visitor visitor;
boost::apply_visitor(visitor, type);

Is it possible to change the visitor such that it receives extra data as follows:

class Append: public boost::static_visitor<>
{
public:
    void operator()(int, const std::string&)
    {}

    void operator()(double, const std::string&)
    {}
};

This string value changes during the lifetime of the Append object. Passing the string in via the constructor is not an option in this case.

like image 425
Baz Avatar asked Oct 18 '12 12:10

Baz


2 Answers

The "additional argument" that gets given to each call is the this pointer. Use it to pass whatever additional information that you need:

#include <boost/variant.hpp>
typedef boost::variant<int, double> Type;
class Append: public boost::static_visitor<>
{
public:
    void operator()(int)
    {}

    void operator()(double)
    {}
    std::string argument;
};

int main() {
    Type type(1.2);
    Append visitor;
    visitor.argument = "first value";
    boost::apply_visitor(visitor, type);
    visitor.argument = "new value";
    boost::apply_visitor(visitor, type);
}
like image 70
Mankarse Avatar answered Nov 05 '22 17:11

Mankarse


Another option is to bind the extra arguments. You visitor class could look like this:

class Append: public boost::static_visitor<>
{
public:
    void operator()(const std::string&, int)
    {}

    void operator()(const std::string&, double)
    {}
};

Call it like so:

std::string myString = "foo";
double value = 1.2;
auto visitor = std::bind( Append(), myString, std::placeholders::_1 );
boost::apply_visitor( visitor, value );
like image 5
Mike Avatar answered Nov 05 '22 15:11

Mike