c++ - 具有多个参数的 boost::static_visitor

标签 c++ boost boost-variant

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);

是否可以更改访问者,使其接收如下额外数据:

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

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

此字符串值在 Append 对象的生命周期内发生变化。在这种情况下,通过构造函数传递字符串不是一个选项。

最佳答案

每次调用的“附加参数”是 this 指针。使用它来传递您需要的任何其他信息:

#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);
}

关于c++ - 具有多个参数的 boost::static_visitor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12954852/

相关文章:

c++ - 我将如何对列表进行排序并获得前 K 个元素? (STL)

c++ - shared_ptr - 按值传递与按引用传递

c++ - 升压::变体 - "no matching function for call"

c++ - std::forward 转发函数

c++ - 线程安全队列给出段错误

c++ - 使用 getline 和分层结构时为 "invalid use of ‘struct main()"

c++ - c++ boost库中的累加器有什么用?

C++ 多线程服务器帮助

c++ - 如何改变 boost::variant operator < 的行为

c++ - 如何获取当前持有的变体类型,并定义该类型的新变量