【问题标题】:Template friend function instantiation模板友元函数实例化
【发布时间】:2013-08-01 19:38:07
【问题描述】:

为什么我会收到以下链接错误?

template<typename T, typename U>
class A {
public:
    class B;
};

template<typename T, typename U>
class A<T, U>::B {
    friend bool operator==(const B& b1, const B& b2);
};

template<typename T, typename U>
bool operator==(const typename A<T, U>::B& b1, const typename A<T, U>::B& b2) {
    return true;
}

int main() {
    A<char, int>::B b1;
    A<char, int>::B b2;

    if (b1 == b2) {
        return 0;
    } else {
        return 1;
    }
}

我得到的错误是:

Undefined symbols for architecture x86_64:
  "operator==(A<char, int>::B const&, A<char, int>::B const&)", referenced from:
      _main in test-qSCyyF.o

【问题讨论】:

    标签: c++ function templates friend friend-function


    【解决方案1】:

    因为你在调用它而它没有定义!

    这个

    template<typename T, typename U>
    class A<T, U>::B {
        friend bool operator==(const B& b1, const B& b2);
    };
    

    A&lt;T,U&gt;::B 类的非模板友元函数的声明。

    它与调用 (b1 == b2) 以及您进一步定义的模板运算符匹配,但它是首选,因为它是非模板。

    GCC 甚至使用-Wnon-template-friend 发出警告

    警告:友元声明 'bool operator==(const A::B&, const A::B&)' 声明了一个非模板函数 [-Wnon-template-friend]
    注意:(如果这不是您想要的,请确保函数模板已经声明并在此处的函数名称后添加 )

    为了修复,它提供了定义

    template<typename T, typename U>
    class A<T, U>::B {
        friend bool operator==(const B& b1, const B& b2) {
            return true;
        }
    };
    

    去掉模板化的操作符,或者只保留一个模板。

    【讨论】:

    • 那么……我该如何解决。 =P
    • 所以我不能有一个在类之外定义的模板化友元函数??
    • @fumoboy007 你通常可以,但在你的情况下,使用嵌套的非模板类?我不这么认为,但我不确定 :) 我会说你不需要它,但我不知道你想要实现什么。
    • 我修改了我的层次结构,这样我就不再有那个嵌套类了。谢谢你的帮助! =)
    猜你喜欢
    • 1970-01-01
    • 2021-07-22
    • 2020-08-20
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多