【发布时间】:2015-04-14 03:25:55
【问题描述】:
我有类似下面的代码。
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
}
};
【问题讨论】:
-
你想用
anotherStr做什么? -
为什么不把
anotherStr传递给d_string_int_visitor的构造函数然后使用呢? -
Preatorian 和 Yakk 的解决方案不是通用的;它们之所以起作用,只是因为额外参数的类型是有界类型之一。这就是所谓的二元(多)访问。如果额外类型不是有界类型,则唯一的解决方案是使用构造函数和成员变量,正如 Nawaz 指出的那样。
标签: c++ c++11 boost c++14 boost-variant