模板警告和错误帮助,(gcc)

时间:2010-05-15 05:44:51

标签: c++ templates gcc warnings

我正在处理容器类模板(对于int,bool,字符串等),我一直坚持这个错误

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

本节

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

我到底做错了什么?。

也不确定此警告信息的含义。

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

在这个位置

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

2 个答案:

答案 0 :(得分:2)

在第一种情况下,您只是第一次说Container而不是Container<T>

在第二种情况下,我认为你需要重复template:虽然模板类的成员函数是隐式模板化的,但朋友函数不是必需的,所以有必要更明确地说明。我不确定你为此目的需要什么样的语法,但我认为它是:

    课前
  • template<typename T> bool operator==(
  • 课程中的
  • bool operator==<>(

我认为这是错误信息试图表达的内容,但并不是非常清楚。

答案 1 :(得分:1)

在第一种情况下,你做了倒退的事情。指定返回类型时,必须将模板参数列表包含在模板标识符(Container<T>)中,但是当指定参数类型时,则不需要执行此操作(仅Container是足够)

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

你出于某种原因反过来做了。

在第二种情况下,当您将operator ==声明为朋友时,它只是警告您,在这种情况下,您所指的operator ==是一个普通的函数。它不能是模板的专业化。即对于类Container<int>函数

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

将成为朋友。但功能模板的专业化

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

成为Container<int>的朋友。如果那是你的意图,你就可以了。

如果您想与上述模板的特定专业化成交,那么您必须说

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

如果您想与上述模板的所有专业化成交,那么您必须说

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