12
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 对象的生命周期内发生变化。在这种情况下,通过构造函数传入字符串不是一种选择。

4

3 回答 3

19

给每个调用的“附加参数”是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);
}
于 2012-10-18T12:49:37.093 回答
5

另一种选择是绑定额外的参数。您的访问者类可能如下所示:

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

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

像这样称呼它:

std::string myString = "foo";
double value = 1.2;
auto visitor = std::bind( Append(), myString, std::placeholders::_1 );
boost::apply_visitor( visitor, value );
于 2018-11-16T18:31:57.363 回答
1

这个解决了你的问题:

#include <iostream>
#include <string>
#include <boost/variant.hpp>

typedef boost::variant<int, double> Type;
typedef boost::variant<const std::string> Extra;
class Append: public boost::static_visitor<>
{
public:
    void operator()(const int& a1, const std::string& a2) const {
        std::cout << "arg 1 = "<< a1 << "\n";
        std::cout << "arg 2 = "<< a2 << "\n";
    }

    void operator()(const double& a1, const std::string& a2) const {
        std::cout << "arg 1 = "<< a1 << "\n";
        std::cout << "arg 2 = "<< a2 << "\n";
    }
};

int main()
{
    Type type(1.2);
    Extra str("extra argument");
    boost::apply_visitor(Append(), type, str);
}

这是一个工作Demo。您可以发送额外的参数 - 任意数量。限制是它们必须被包裹在 boost::variant 中。但是,编译器会优化内部具有单一类型的变体。如果您需要两个以上的参数#include <boost/variant/multivisitors.hpp>,请参阅https://www.boost.org/doc/libs/1_70_0/doc/html/boost/apply_visitor.html

于 2019-06-08T16:16:33.490 回答