强制实例化友元函数

Force instantiation of friend functions

本文关键字:函数 友元 实例化      更新时间:2023-10-16

假设我们有一个带友元函数的模板类:

template<class T>
class A {
    friend A operator+ (int, const A&);
};

这个函数在下面某处实现:

template<class T>
A<T> operator+ (int i, const A<T>& a) {
    ...
}

下面还有一个模板类的强制实例化:

template class A<int>;

这是否意味着operator+(int, A<int>)将被编译?或者我必须单独强制实例化它来实现这一点?

模板参数不会自动转发给friend声明。您还需要为该函数指定一个模板参数:

template<class T>
class A {
    template<class U>
    friend A<U> operator+ (int, const A<U>&);
};

实现基本正确,应该是

template<class T>
A<T> operator+ (int i, const A<T>& a) {
                           // ^^^
    // ...
}