Re: How to write output function for template classes?
On 11/16/2011 12:54 PM, Jayden Shui wrote:
Hello All,
I have a code like:
template<class T, char open, char close>
class Enclosed
{
public:
Enclosed(T& t) : mT(t) {}
friend ostream& operator<<(ostream& os, Enclosed const& e);
private:
T& mT;
};
template<class T, char open, char close>
ostream& operator<<(ostream& os, Enclosed<T, open, close> const& e)
{
os<< open<< e.mT<< close;
return os;
}
When I test it by
cout<< Enclosed<int, '[', ']'>(5);
The compiler said they can not find the operator<< function. Would
you please help me to look into it?
-------------------------------------------- >8 cut here
#include <iostream>
using namespace std;
template<class T, char open, char close>
class Enclosed
{
public:
Enclosed(T& t) : mT(t) {}
friend ostream& operator<<(ostream& os, Enclosed const& e);
private:
T& mT;
};
template<class T, char open, char close>
ostream& operator<<(ostream& os, Enclosed<T, open, close> const& e)
{
os << open << e.mT << close;
return os;
}
int main()
{
cout << Enclosed<int, '[', ']'>(5);
}
-------------------------------------------- >8 cut here
Comeau says
"ComeauTest.c", line 11: warning: "std::ostream &operator<<(std::ostream
&, const
Enclosed<T, open, close> &)" declares a non-template function
-- add
<> to refer to a template instance
friend ostream& operator<<(ostream& os, Enclosed const& e);
^
"ComeauTest.c", line 26: error: no instance of constructor "Enclosed<T,
open,
close>::Enclosed [with T=int, open='[', close=']']" matches the
argument list
The argument types that you used are: (int)
cout << Enclosed<int, '[', ']'>(5);
^
You declare a non-template operator<< as the friend of your class
template and then you define a template function... See FAQ 35.16.
BTW, you need to make your Enclosed take a 'const T&' if you want to use
it with the literal like '5'.
V
--
I do not respond to top-posted replies, please don't ask