c++ - 使用额外参数 boost 变体访问者

标签 c++ c++11 boost c++14 boost-variant

我有类似于下面的代码。

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

MsgValue v;

与其这样说,

IntValue value = boost::apply_visitor(d_string_int_visitor(), v);

我想像这样传递一个额外的参数:但是 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
    }
};

最佳答案

您可以使用 std::bind 将额外的 string 参数绑定(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;
    }
};

现在创建一个已绑定(bind)第二个 string 参数的访问者。

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

Live demo

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

关于c++ - 使用额外参数 boost 变体访问者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29618636/

相关文章:

c++ - 即使在正确的目录中也找不到头文件?

java 基本 : the Template can only accept one dimension change why?

c++ - 现代 C++ 的实验特性对于长期项目是否可靠?

c++ - 在 qi spirit 中回滚替代解析器的变化

c++ - 优化级别为 -O2 的 boost::any_range 导致崩溃

c++ - Boost::Python: 没有找到 C++ 类型的转换器:boost::python::detail::kwds_proxy

c++ - 查找使用球坐标表示的线段之间的距离

c++ - 编译器何时在 C++ 中移动/复制?

c++ - 动态数值系列

boost - python和java api : undefined symbol: _ZN5boost6system15system_categoryEv的释放错误