I'm trying to overload the << operator for a class template, but the compiler gives me a linker error. The goal is to be able to send a de-referenced base class pointer to std::cout so that the derived operator<< gets called.
Is this possible?
class IBase
{
public:
IBase() {};
virtual ~IBase() {};
};
template <typename T>
class Derived
: public IBase
{
public:
Derived(T data);
friend std::ostream& operator<<(std::ostream& os, const Derived<T>& dt);
private:
T data_;
};
template <typename T>
Derived<T>::Derived(T data)
: IBase(),
data_(data)
{
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const Derived<T>& dt)
{
os << dt.data_;
return os;
}
int _tmain(int argc, _TCHAR* argv[])
{
// Question 1
Derived<int> der(234);
std::cout << der;
// Question 2
//IBase* base = new Derived<int>(5);
// std::cout << *base
}
Here are the errors:
error LNK2001: unresolved external symbol "class std::basic_ostream > & __cdecl operator<<(class std::basic_ostream
&,class Derived const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$Derived@H@@@Z)
and
fatal error LNK1120: 1 unresolved externals