S
syang8
Dear all,
I am trying to design classes with stream support. Basically, I want
the operator << work for the base class and all the derived classes.
If the base class is a template class, and the operator << is also
designed as a template function. The program has following linking
errors:
"error LNK2019: unresolved external symbol "class
function _main"
However, if the base class is not a template class. Everything is ok
and the link error dosen't exist. Note that I tried instantiate the
operator << explicitly. But it doesn't solve the problem.
Here are the example codes:
----------------------------------------------------------------------------------------------------------------------------------------------------
#include <iostream>
#include <string>
using namespace std;
template<class T>
class Base
{
public:
friend ostream& operator << (ostream&, const Base&);
virtual string get_buffer() const {return "Base class";}
};
class Derived : public Base<bool>
{
public:
virtual string get_buffer() const {return "Derived class";}
};
template<class T>
ostream& operator << (ostream& os, const Base<T>& a)
{
os << a.get_buffer();
return os;
}
/*
template<>
ostream& operator << (ostream& os, const Base<bool>& a)
*/
int main()
{
Derived b;
cout << b << endl;
}
I am trying to design classes with stream support. Basically, I want
the operator << work for the base class and all the derived classes.
If the base class is a template class, and the operator << is also
designed as a template function. The program has following linking
errors:
"error LNK2019: unresolved external symbol "class
$char_traits@D@std@@@std@@AAV01@ABV?$Base@_N@@@Z) referenced instd::basic_ostream said:&,class Base<bool> const &)" (??6@YAAAV?$basic_ostream@DU?
function _main"
However, if the base class is not a template class. Everything is ok
and the link error dosen't exist. Note that I tried instantiate the
operator << explicitly. But it doesn't solve the problem.
Here are the example codes:
----------------------------------------------------------------------------------------------------------------------------------------------------
#include <iostream>
#include <string>
using namespace std;
template<class T>
class Base
{
public:
friend ostream& operator << (ostream&, const Base&);
virtual string get_buffer() const {return "Base class";}
};
class Derived : public Base<bool>
{
public:
virtual string get_buffer() const {return "Derived class";}
};
template<class T>
ostream& operator << (ostream& os, const Base<T>& a)
{
os << a.get_buffer();
return os;
}
/*
template<>
ostream& operator << (ostream& os, const Base<bool>& a)
*/
int main()
{
Derived b;
cout << b << endl;
}