C++ 运算符==为好友时的链接器错误
下面的代码是重现我的问题的最低限度的代码。当我试图编译它时,链接器找不到C++ 运算符==为好友时的链接器错误,c++,templates,linker,friend,C++,Templates,Linker,Friend,下面的代码是重现我的问题的最低限度的代码。当我试图编译它时,链接器找不到Config的operator==: Undefined symbols for architecture x86_64: "operator==(Config<2> const&, Config<2> const&)", referenced from: _main in test2.o 这里的问题是什么?您没有在朋友声明中声明模板: template <
Config
的operator==
:
Undefined symbols for architecture x86_64:
"operator==(Config<2> const&, Config<2> const&)", referenced from:
_main in test2.o
这里的问题是什么?您没有在
朋友声明中声明模板:
template <int DIM>
class Config{
template <int DIM_> // <<<<
friend bool operator==(const Config<DIM_>& a, const Config<DIM_>& b);
public:
int val;
};
模板
类配置{
template//解决了这个问题,但我不知道为什么必须将其显式定义为模板。@Michael,因为如果不是这样,你就不是在和模板操作符交朋友,而是在交朋友(并声明)只是一些特定的运算符==与类模板交朋友。朋友函数只是类之外将其声明为朋友的任何普通函数。现在,只需将朋友声明复制到类之外,删除friend
,您就会看到它与您编写的模板函数不匹配。顺便说一句,我编写了function因为运算符只是一个具有特殊调用语法的函数。所以我必须告诉编译器:“请寻找一个模板,而不是一个普通的非模板函数。”?@Michael更新了我的答案。
template <int DIM>
class Config{
template <int DIM_> // <<<<
friend bool operator==(const Config<DIM_>& a, const Config<DIM_>& b);
public:
int val;
};