当前位置: 首页 > 知识库问答 >
问题:

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

松新
2023-03-14

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

体系结构x86_64的未定义符号:" operator==(foo const

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;
}

共有3个答案

蒙经纶
2023-03-14

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

template<typename V>
friend bool operator==(const foo<V> &lhs, const foo<V> &rhs);
孙光临
2023-03-14

< code>operator==是一个函数模板,但是友谊声明没有反映这一点。这是解决问题的一种方法:

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

一个非常小的故障是它给< code>operator==

太叔志尚
2023-03-14

下面是代码的修复:

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;
};
 类似资料:
  • 我认为我的模板使用不当,但我不知道我做错了什么。这就像模板链表无法确定它需要使用我的术语类一样。 名单- 以下是Visual Studio 2012的确切错误: > 错误LNK1120:1未解决的外部C:\用户\迈克尔\文档\魔术公文包\尚普兰\课程工作\数据结构\pa2\调试\pa2.exe 标题。H 功能。cpp 链接列表。H 术语h

  • 考虑以下头文件和源文件: 我在

  • 英文原文: http://emberjs.com/guides/templates/links/ 链接 ({{link-to}}助手) 你可以使用如下的方式创建一个指向一个路由的链接: 1 2 3 4 5 App.Router.map(function() { this.resource("photos", function(){ this.route("edit", { path:

  • 嘿,伙计们,我在安装了react native payola包装后制作了一个react native应用程序,我面临这个问题 如何解决这些错误......

  • 我尝试在 gcc 6.0 的开发中实际使用新的 c 1z 功能。 如果我尝试这个小例子: 我得到了: gcc 版本是快照 Linux-gnu_6-20151011 有什么提示如何链接新的c 1z功能吗?

  • 来自Lippman et al C Primer第5版,第16.1.2节: 第一个问题:排队 为什么是<代码> 我添加了以下代码来定义运算符==并实例化类模板。它成功编译和链接: 如果我删除