为什么这段代码会给我一个链接器错误,我该如何解决?
架构 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/