【发布时间】:2017-09-27 12:08:25
【问题描述】:
我正在尝试编写自己的向量模板类,但是在编写友元函数声明时遇到了一些问题。
一开始我是这样写的:
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> 的好友函数。
在模板类中编写友元函数的正确方法是什么?
【问题讨论】:
标签: c++ templates vector friend