Your immediate problem is that the operator needs to be templated.
However, your ultimate goal can't be attained through templates alone as dereferencing a IBase*
gets you a IBase&
- template instantiation occurs at compile time and the compiler has no access to the runtime type.
So your templated operator will never be used if you pass a dereferenced IBase*
to operator <<
.
Instead, add a virtual output function to the base and override it:
class IBase
{
public:
IBase() {};
virtual ~IBase() {};
virtual std::ostream& output(std::ostream&) const = 0;
};
template
class Derived
: public IBase
{
public:
Derived(T data);
virtual std::ostream& output(std::ostream& os) const
{
os << data;
return os;
}
private:
T data_;
};
std::ostream& operator<<(std::ostream& os, const IBase& dt)
{
return dt.output(os);
}