Re: Generic ostream operator<<?
I still believe the solution with polymorphism is clearer and closer to what the initial requirement for a generic operator<< function was.
struct printable
{
virtual std::ostream& print(std::ostream&) const = 0;
};
std::ostream& operator<<(std::ostream& out, const printable& p)
{
return p.print(out);
}
Having the above definitions, any class can now inherit printable and implement the print method. Advantages:
1. No template tricks needed.
2. Imposes a definition on the class by making it "IS-A" printable - which is sort of consistent with what it does.
3. Imposes a restriction on how the print method should be implemented in a class - makes code consistent.
Example:
class Foo : public printable
{
public:
std::ostream& print(std::ostream& out) const
{
return out << "Hello foo";
}
};
class Bar : public printable
{
public:
std::ostream& print(std::ostream& out) const
{
return out << "Hello bar";
}
};
And use like:
std::cout << f << std::endl << Bar() << std::endl;
SD
On Wednesday, June 20, 2012 1:00:00 AM UTC+5:30, Gerhard Fiedler wrote:
Hello,
I want to be able to stream custom classes to ostreams like this:
MyClass foo;
myStream << foo;
AIUI, this requires an operator<<() with this signature:
std::ostream &operator<<( std::ostream &str, MyClass const &printable );
In order to avoid creating such a function for every class, I tried a
template like this:
template < class Printable >
std::ostream &operator<<( std::ostream &stream,
Printable const &printable )
{
printable.print( stream );
return stream;
}
(All the classes in question have a public member function "void print(
std::ostream &stream )".)
However, with this I get tons of errors like "'operator <<' is
ambiguous".
Is there a way to define this template function so that it is only
instantiated for classes that implement this print() function? (I could
make the name such that it is very unlikely that any other class has
such a name.)
Or is there another way to avoid having to define such a global
operator<< for every class with ostream support?
Thanks,
Gerhard