链接器错误:模板关系运算符

Linker error: Template relational operator

本文关键字:关系 运算符 错误 链接      更新时间:2023-10-16

为什么这段代码会给我一个链接器错误,我如何修复它?

架构x86_64的未定义符号:"operator==(foo const&, foo const&)",引用自main中的:_main。x86_64

template<typename T>
class foo {
  //friends get access to the private member t
  friend bool operator==(const foo<T> &lhs, const foo<T> &rhs);
  T t;
};
template<typename T>
bool operator==(const foo<T> &lhs, const foo<T> &rhs) {
  return lhs.t == rhs.t;
}
int main(int,char**) {
  foo<int> f1, f2;
  if (f1 == f2)
    ;
  return 0;
}

这是你的代码修复:

template<typename T>
class foo; // Forward declaration
template<typename T> // Need to define or declare this before the class
bool operator==(const foo<T> &lhs, const foo<T> &rhs) {
  return lhs.t == rhs.t; 
}
template<typename T>
class foo {
  // Notice the little <> here denoting a specialization
  friend bool operator==<>(const foo<T> &lhs, const foo<T> &rhs);
  T t;
};

operator==是一个函数模板,但是友谊声明没有反映这一点。这是修复它的一种方法:

template <class U>
friend bool operator==(const foo<U> &lhs, const foo<U> &rhs);

一个非常小的故障是它给operator==<int>朋友访问foo<string>。出于这个原因,我认为@JesseGood的修复更简洁,尽管(矛盾的是)更啰嗦。

您需要再次指定模板类型,但与类模板类型不同:

template<typename V>
friend bool operator==(const foo<V> &lhs, const foo<V> &rhs);

重载操作符时,避免使用友元函数;您需要将函数定义为公共类成员,并使其只接受一个参数(而不是两个)。

template<typename T>
class foo {
  //public function allowing access to the private member t
  public:
  bool operator==(  foo<T> &rhs)
  {
      return t == rhs.t;
  }
  private:
  T t;
};

int main(int,char**) {
  foo<int> f1, f2;
  if (f1 == f2)
    ;
  return 0;
}