我的项目正在使用boost::hold_any
。虽然它对现有类型没有问题,但它不适用于自定义类。例如:
#include <iostream>
#include <string>
#include <boost\spirit\home\support\detail\hold_any.hpp>
class Foo
{
public:
Foo(){}
~Foo(){}
int Bar;
};
int main(int argc, char *argv[])
{
Foo A;
boost::spirit::hold_any B(A); // ERROR C2678 HERE
}
导致此错误
error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::basic_istream<char,std::char_traits<char>>' (or there is no acceptable conversion)
我已经尝试了一些重载,但它们不起作用(在类级别声明)。
std::basic_istream<char>& operator>>(std::basic_istream<char>& is);
std::basic_istream<char> operator>>(std::basic_istream<char> is);
如何创建可与boost::hold_any
一起使用的类?
回复评论
在类级别声明std::basic_istream<char>& operator>>(std::basic_istream<char>&, Foo&);
导致error C2804: binary 'operator>>' has too many parameters
并在全局范围内声明导致错误error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const Foo' (or there is no acceptable conversion)
答案 0 :(得分:1)
boost::spirit::hold_any
需要流操作符(因为它是解析器库的未记录的实现细节)。为了使用它,你必须为Foo定义它们:
std::istream &operator>>(std::istream &in, Foo &dest) {
// read a Foo from in into dest
return in;
}
std::ostream &operator<<(std::ostream &out, Foo const &src) {
// write src to out
return out;
}
...或者您可以使用boost::any
所基于的boost::spirit::hold_any
替换,但没有此要求。它可以找到here。如果使用boost::any
确实是一个问题。