lundi 28 septembre 2015

Redirection from/to stream with intermediate class redirection

Suppose I can do ostream << Intermediate and I can do Intermediate << Example, can I do ostream << Example without adding a special overloading of operator<< from Example to ostream? Alternatively, is there any other approach I can use to support both serialization/deserialization using a intermediate class and still remove boilerplate? The following was my attempt:

#include <iostream>
#include <sstream>

using namespace std;

class Intermediate
{
};

ostream & operator<<(ostream &stream, const Intermediate& intermediate)
{
  (void)intermediate;
  return stream;
}

istream & operator>>(istream &stream, const Intermediate& intermediate)
{
  (void)intermediate;
  return stream;
}

class Example
{
};

Intermediate & operator<<(Intermediate &intermediate, const Example &example)
{
  (void)example;
  return intermediate;
}

Intermediate & operator>>(Intermediate &intermediate, Example &example)
{
  (void)example;
  return intermediate;
}

int main()
{
  stringstream stream;
  Intermediate intermediate;
  Example example;

  intermediate << example; // WORKS
  stream << intermediate; // WORKS

  stream << example; // ERROR

  return 0;
}

The error is cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’. c++11 compiler is enabled.

Aucun commentaire:

Enregistrer un commentaire