Template confusion

  • Thread starter Michael W. Hicks
  • Start date
M

Michael W. Hicks

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
 
V

Victor Bazarov

Michael W. Hicks said:
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.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top