使用额外参数增加变体访问者

Iva*_*van 8 c++ boost boost-variant c++11 c++14

我有类似下面的代码.

typedef uint32_t IntType;
typedef IntType IntValue;
typedef boost::variant<IntValue, std::string>  MsgValue;

MsgValue v;
Run Code Online (Sandbox Code Playgroud)

而不是说这个,

IntValue value = boost::apply_visitor(d_string_int_visitor(), v);
Run Code Online (Sandbox Code Playgroud)

我想传递一个额外的参数,如下所示:但是operator()给出了编译错误.

//This gives an error since the overload below doesn't work.
IntValue value = boost::apply_visitor(d_string_int_visitor(), v, anotherStr);

class d_string_int_visitor : public boost::static_visitor<IntType>
{
public:
    inline IntType operator()(IntType i) const
    {
        return i;
    }

    inline IntValue operator()(const std::string& str) const noexcept
    {
        // code in here
    }

    //I want this, but compiler error.
    inline IntValue operator()(const std::string& str, const std::string s) const noexcept
    {
        // code in here
    }
};
Run Code Online (Sandbox Code Playgroud)

Pra*_*ian 8

您可以使用将绑定string参数绑定到访问者std::bind.首先,将std::string参数添加到所有访问者的operator()重载中.

class d_string_int_visitor : public boost::static_visitor<IntType>
{
public:
    inline IntType operator()(IntType i, const std::string& s) const
    {
        return i;
    }

    inline IntValue operator()(const std::string& str, const std::string& s) const noexcept
    {
        // code in here
        return 0;
    }
};
Run Code Online (Sandbox Code Playgroud)

现在创建一个绑定了第二个string参数的访问者.

auto bound_visitor = std::bind(d_string_int_visitor(), std::placeholders::_1, "Hello World!");
boost::apply_visitor(bound_visitor, v);
Run Code Online (Sandbox Code Playgroud)

现场演示

但是,更好的解决方案是将字符串作为访问者的构造函数参数传递.