当operator ==是朋友时,链接器错误 [英] Linker error when operator== is a friend

查看:103
本文介绍了当operator ==是朋友时,链接器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是重现我的问题的最低代码.当我尝试编译它时,链接器找不到Configoperator==:

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

operator==Config的朋友.但是,当我不再将operator==声明为朋友时,代码编译器将没有错误.

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

这是什么问题?

推荐答案

您错过了在friend声明中声明模板的方法:

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

如果要使用friend函数声明,则必须使用它的确切签名声明.如果这涉及模板参数,则必须与封闭的模板类或结构无关地指定这些参数.

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.

这是一个精妙的答案,深入解释了friend声明的几个方面.

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

这篇关于当operator ==是朋友时,链接器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆