Baz*_*Baz 10 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);
Run Code Online (Sandbox Code Playgroud)
是否可以更改访问者,以便它接收如下额外数据:
class Append: public boost::static_visitor<>
{
public:
void operator()(int, const std::string&)
{}
void operator()(double, const std::string&)
{}
};
Run Code Online (Sandbox Code Playgroud)
此字符串值在Append对象的生命周期内更改.在这种情况下,通过构造函数传递字符串不是一个选项.
Man*_*rse 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);
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是绑定额外的参数。您的访问者类可能如下所示:
class Append: public boost::static_visitor<>
{
public:
void operator()(const std::string&, int)
{}
void operator()(const std::string&, double)
{}
};
Run Code Online (Sandbox Code Playgroud)
像这样称呼它:
std::string myString = "foo";
double value = 1.2;
auto visitor = std::bind( Append(), myString, std::placeholders::_1 );
boost::apply_visitor( visitor, value );
Run Code Online (Sandbox Code Playgroud)