且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在模板类中编写朋友函数声明的正确方法是什么?

更新时间:2022-01-29 22:26:05

朋友非模板功能

但是编译器报告警告,我声明了一个非模板函数.

But the compiler reports a warning that I declare a non-template function.

是的,您要在类定义中声明一个非模板函数.这意味着,如果您在类定义之外定义它,则必须将其定义为非模板函数,并针对所有可能的实例进行定义,例如:

Yes, you're declaring a non-template function inside the class definition. That means if you define it out of the class definition, you have to define it as non-template function, and for all the possible instantiations , like:

bool operator==(const vector<int>& v1, const vector<int>& v2)
{
    ...
}
bool operator==(const vector<char>& v1, const vector<char>& v2)
{
    ...
}

这很丑陋,您可以在类定义中定义它,例如

That is ugly, you can define it inside the class definition like

template <typename T, typename Alloc = std::allocator<T>>
class vector {
public:
    friend bool operator==(const vector<T, Alloc>&, const vector<T, Alloc>&) {
        ...
    }
};

朋友功能模板

如果要将其定义为模板函数,并限制友谊范围,则可以

Friend function template

If you want to define it as template function, and constrain the scope of friendship, you can

// forward declaration
template <typename T, typename Alloc>
class vector;

// forward declaration
template <typename T, typename Alloc>
bool operator==(const vector<T, Alloc>& v1, const vector<T, Alloc>& v2);

template <typename T, typename Alloc = std::allocator<T>>
class vector {
private:
    int i;
public:
    // only the instantiation of operator== with template parameter type of current T and Alloc becomes friend
    friend bool operator==<>(const vector<T, Alloc>& v1, const vector<T, Alloc>& v2);
};

template <typename T, typename Alloc = std::allocator<T>>
bool operator==(const vector<T, Alloc>& v1, const vector<T, Alloc>& v2)
{
    ...
}

然后,对于vector<int>,只有bool operator==(const vector<int>&, const vector<int>&)是朋友,而其他实例化(例如bool operator==(const vector<double>&, const vector<double>&))则不是.

Then, for vector<int>, only bool operator==(const vector<int>&, const vector<int>&) is friend, other instantiations like bool operator==(const vector<double>&, const vector<double>&) is not.

实时