我有类似于下面的代码。
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);
但是,更好的解决方案是将字符串作为访问者的构造函数参数传递。
关于c++ - 使用额外参数 boost 变体访问者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29618636/