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

What is the right way to write friend function declarations in template class?

我正在尝试编写自己的矢量模板class,但是在编写友元函数声明时遇到了一些问题。

一开始我是这样写的:

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

但是编译器报警告说我声明了一个非模板函数。所以我将朋友声明更改为:

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

到目前为止一切都很好,但我认为仍然存在问题。如果我这样写,我会创建所有 operator== 函数,这些函数将两个模板参数作为其友元函数。例如,operator==(const vector<int>&, const vector<int>&)operator==(const vector<double>&, const vector<double>&) 都是 vector<int> 的友元函数。

在模板中写友元函数的正确方法是什么class?

好友非模板函数

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

是的,您在 class 定义中声明了一个非模板函数。这意味着如果你在 class 定义之外定义它,你必须将它定义为非模板函数,并且对于所有可能的实例化,如:

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

太丑了,你可以在class定义里面定义它,比如

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

好友功能模板

如果想定义为模板函数,限制友情范围,可以

// 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>&)不是。

LIVE