c++ - 创建一个可以与 boost::hold_any 一起使用的类

标签 c++ boost

我的项目正在使用 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&);在类(class)原因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)

最佳答案

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 对您来说确实是个问题。

关于c++ - 创建一个可以与 boost::hold_any 一起使用的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27523630/

相关文章:

c++ - Asio 的计时器在取消时什么时候会抛出异常?

c# - 为什么将此代码片段从 C# 转换为 C++ 会降低性能?

C++:使用具有特定(双...)指针参数的函数重载具有void *函数的函数

Android - 找不到 CMake

c++ - 为什么我对数组中的图 block 进行评分的函数不起作用?

c++ - 尝试使用 boost 读取 xml 时出现空指针

c++ - 实际上什么返回类型有一个新的?

c++ - 生产者/消费者实现——需要反馈

c++ - 安全中断 C++11 阻塞操作

c++ - 抛出一个 std::length_error 实例,示例需要 boost