c++ - 链接器错误 : Template relational operator

标签 c++ templates

为什么这段代码会给我一个链接器错误,我该如何解决?

架构 x86_64 的 undefined symbol :“operator==(foo const&, foo const&)”,引用自:_main in main.o ld: symbol(s) not found for architecture 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;
};

关于c++ - 链接器错误 : Template relational operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17023755/

相关文章:

C++ 模板成员函数已定义为相同类型

c++ - 初始化涉及 vector 数据类型的变量

安卓设计模板

c++ - 通过不返回引用来防止下标运算符赋值会导致运行时崩溃

c++ - 模板 C++0x lambda 函数……还是仿函数/谓词?

c++ - Qt : Cannot open include file: 'QtSql' : No such file or directory

c++ - VexCL: vexcl vector 中最大值的索引

c++ - 模板外部链接不起作用

c++ - 抓老鼠?

c++ - 是否未指定在未评估的上下文中实例化模板/lambda?