Linker error when operator== is a friend [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-12-24 02:37:29

问题


The following code is a minimum code to reproduce my problem. When I try to compile it, the linker can not find operator== for Config:

Undefined symbols for architecture x86_64:
"operator==(Config<2> const&, Config<2> const&)", referenced from:
          _main in test2.o

The operator== is a friend of Config. BUT when I do no longer declare operator== as a friend, the code compilers with no error.

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;
}

What is the problem here?


回答1:


You have missed to declare the template in the friend declaration:

template <int DIM>
class Config{
    template <int DIM_> // <<<<
    friend bool operator==(const Config<DIM_>& a, const Config<DIM_>& b);

    public:
        int val;
};

If you want to have a friend function declaration you must use it's exact signature declaration. If this involves template parameters these must be specified independently from the enclosing template class or struct.


Here's a brilliant answer explaining the several aspects of friend declarations in depth.



来源:https://stackoverflow.com/questions/30014033/linker-error-when-operator-is-a-friend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!