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对象的生命周期内发生更改。在这种情况下,通过构造函数传递字符串不是一个选项。
答案 0 :(得分:16)
为每个调用赋予的“附加参数”是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);
}
答案 1 :(得分:2)
另一个选择是绑定额外的参数。您的访客班级可能看起来像这样:
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 );
答案 2 :(得分:0)
这个解决了您的问题:
#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