当operator ==是朋友时,链接器错误

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)

这里有什么问题?

πάν*_*ῥεῖ 6

您错过了在声明中声明模板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,深入解释了声明的几个方面.