Soapy
Soapy

Reputation: 567

Creating a class that can be used with boost::hold_any

My project is using boost::hold_any. While it's okay for existing types, it does not work with custom classes. For example:

#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
}

causes this error

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)

I have already tried some overloads but they do not work (declared at class level).

std::basic_istream<char>& operator>>(std::basic_istream<char>& is);
std::basic_istream<char> operator>>(std::basic_istream<char> is);

How can I create a class that can be used with boost::hold_any?


Reply to comment

Declaring std::basic_istream<char>& operator>>(std::basic_istream<char>&, Foo&); at class level causes error C2804: binary 'operator>>' has too many parameters and declaring at global scope results in the error error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const Foo' (or there is no acceptable conversion)

Upvotes: 0

Views: 397

Answers (1)

Wintermute
Wintermute

Reputation: 44063

boost::spirit::hold_any requires, as the error message implies, streaming operators (because it is an undocumented implementation detail of a parser library). In order to use it, you will have to define them for 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;
}

...or you could use the boost::any replacement that boost::spirit::hold_any was based on that does not have this requirement. It can be found here. If using boost::any really is a problem for you.

Upvotes: 1

Related Questions