Connecting Tech Pros Worldwide Forums | Help | Site Map

Template confusion

Michael W. Hicks
Guest
 
Posts: n/a
#1: Jul 22 '05
Hello,

Consider the following short code snippet:

template <class TType1> class CA
{
public:
friend ostream& operator<<( ostream &o, CA<TType1> a )
{
// do something reasonable here...
return o;
}
};

template <class TType1> class CB
{
public:
CB()
{
CA<int> Data;
cout << Data << endl;
}
};

int main( int argc, char *argv[] )
{
CB<int> a;
return 1;
}

Can someone explain why MSVC 6.0 informs me that:

error C2679: binary '<<' : no operator defined which takes a right-hand
operand of type 'class CA<int>' (or there is no acceptable conversion)

It appears that the construction of the template member functions isn't
occuring as I would expect. I admit I'm not a compiler expert. What's the
skinny here and what's the best solution? I've found a few solutions but
they all seem convoluted - basically I instance a CA<int> in various other
places or I have CB inherit from CA.

Thanks,
Mike



Victor Bazarov
Guest
 
Posts: n/a
#2: Jul 22 '05

re: Template confusion


"Michael W. Hicks" <mhicks1@speakeasy.net> wrote...[color=blue]
> Consider the following short code snippet:
>
> template <class TType1> class CA
> {
> public:
> friend ostream& operator<<( ostream &o, CA<TType1> a )
> {
> // do something reasonable here...
> return o;
> }
> };
>
> template <class TType1> class CB
> {
> public:
> CB()
> {
> CA<int> Data;
> cout << Data << endl;
> }
> };
>
> int main( int argc, char *argv[] )
> {
> CB<int> a;
> return 1;
> }
>
> Can someone explain why MSVC 6.0 informs me that:
>
> error C2679: binary '<<' : no operator defined which takes a right-hand
> operand of type 'class CA<int>' (or there is no acceptable conversion)
>
> It appears that the construction of the template member functions isn't
> occuring as I would expect. I admit I'm not a compiler expert. What's the
> skinny here and what's the best solution? I've found a few solutions but
> they all seem convoluted - basically I instance a CA<int> in various other
> places or I have CB inherit from CA.[/color]

You should probably declare the function before trying to define it.
Declaring it (and you want it a template) requires to put 'template'
there. That would give your compiler a notion that the function is
actually a template.

template<class T> class CA;
template<class T> ostream& operator<<(ostream&, CA<T> const&);

....

Victor


Closed Thread