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

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

本文关键字:声明 方法 是什么 函数 朋友      更新时间:2023-10-16

我正在尝试编写自己的矢量模板类,但是在编写朋友函数声明时我有一些问题。

起初我这样写了:

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>的朋友函数。

在模板类中编写朋友功能的正确方法是什么?

朋友非网板函数

,但编译器报告了我声明非模板功能的警告。

是的,您正在宣布类定义中的非模板函数。这意味着,如果您将其定义为类定义,则必须将其定义为非模板函数,并且对于所有可能的实例,例如:

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

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

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