链接器错误:模板关系运算符
Linker error: Template relational operator
为什么这段代码会给我一个链接器错误,我如何修复它?
架构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;
}
相关文章:
- 在 c++ 中对字符串进行操作的关系运算符无法按预期工作
- 为什么在C++中使用关系运算符创建的模板函数不能对字符串正常工作?
- 当关系运算符的含义相同时,为什么结果不同?
- C++使用关系运算符比较字符串
- 阐明关系运算符重载的概念(需要调试帮助)
- 迭代器关系运算符出错(带单独链接和迭代器的自定义哈希表)
- C++使用 shared_ptr 但调用了对象的关系运算符?
- C++ 字符 - 关系运算符
- 使用关系运算符比较指针意味着什么
- C++ 如何重载关系运算符以检查两个对象是否相同
- 枚举类的关系运算符重载
- C++ STL 关系运算符如何比较堆栈
- 为什么指针类型的内置关系运算符不生成C++的总顺序?
- 字符串类关系运算符重载
- 与关系运算符的字符串比较(长度不同)
- 对于C++字符串最好使用比较方法或关系运算符
- 用Spirit Qi解析c风格的关系运算符
- 链接器错误:模板关系运算符
- c++中重载二元关系运算符的正确方法
- 这个关系运算符的UML格式是怎样的?