views:

79

answers:

2

Hi there, I'm working on an container class template (for int,bool,strings etc), and I've been stuck with this error

cont.h:56: error: expected initializer before '&' token

for this section

template <typename T>
const Container & Container<T>::operator=(const Container<T> & rightCont){

what exactly have I done wrong there?.

Also not sure what this warning message means.

cont.h:13: warning: friend declaration `bool operator==(const Container<T>&, const Container<T>&)' declares a non-template function
cont.h:13: warning: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) -Wno-non-template-friend disables this warning

at this position

template <typename T>
class Container{
    friend bool operator==(const Container<T> &rhs,const Container<T> &lhs);
public:
+2  A: 

In the first case, you're saying just Container the first time instead of Container<T>.

In the second case, I think you need to repeat the template: while member functions of a template class are implicitly templated, friend functions aren't necessarily, so it's necessary to be more explicitly . I'm not sure what exact syntax you need for that purpose, but I think it is:

  • before the class, template<typename T> bool operator==( etc
  • in the class, bool operator==<>( etc

I think that's what the error message is trying to convey, though not super-clearly.

Alex Martelli
+1  A: 

In the first case you've done things backwards. When you specify the return type, you have to include the template parameter list into the template identifier (Container<T>), but when you specify parameter type, you don't need to do it (just Container is enough)

template <typename T>
const Container<T> & Container<T>::operator=(const Container & rightCont){
   ...

You did it the other way around for some reason.

In the second case, when you declare operator == as a friend it simply warns you that that in this case operator == you are referring to is an ordinary function. It can't be a specialization of a template. I.e. for the class Container<int> the function

bool operator==(const Container<int> &rhs, const Container<int> &lhs) {
  // ...
}

will be a friend. But specialization of function template

template <class U> 
bool operator==(const Container<U> &rhs, const Container<U> &lhs) {
  // ...
}

for U == int will not be a friend of Container<int>. If that's your intent, you are OK.

If you wanted to befriend a specific specialization of the above template, you'd have to say

template <typename T>
class Container {
  friend bool operator==<T>(const Container<T> &rhs, const Container<T> &lhs);
  ...

If you wanted to befriend all specialization of the above template, you'd have to say

template <typename T>
class Container {
  template <class U> 
  friend bool operator==(const Container<U> &rhs, const Container<U> &lhs);
  ...
AndreyT