Mic*_*ael 2 c++ linker templates friend
以下代码是重现我的问题的最小代码.当我尝试编译,链接器无法找到operator==为Config:
Undefined symbols for architecture x86_64:
"operator==(Config<2> const&, Config<2> const&)", referenced from:
_main in test2.o
Run Code Online (Sandbox Code Playgroud)
该operator==是朋友Config.但是,当我不再声明operator==为朋友时,代码编译器没有错误.
template <int DIM>
class Config{
// comment the following line out and it works
friend bool operator==(const Config<DIM>& a, const Config<DIM>& b);
public:
int val;
};
template <int DIM>
bool operator==(const Config<DIM>& a, const Config<DIM>& b){
return a.val == b.val;
}
int main() {
Config<2> a;
Config<2> b;
a == b;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这里有什么问题?
您错过了在声明中声明模板friend:
template <int DIM>
class Config{
template <int DIM_> // <<<<
friend bool operator==(const Config<DIM_>& a, const Config<DIM_>& b);
public:
int val;
};
Run Code Online (Sandbox Code Playgroud)
如果你想要一个friend函数声明,你必须使用它的确切签名声明.如果这涉及模板参数,则必须独立于封闭模板类或结构指定这些参数.
这是一个很好的答案friend,深入解释了声明的几个方面.
| 归档时间: |
|
| 查看次数: |
405 次 |
| 最近记录: |