我正在尝试编写自己的 vector 模板类,但在编写友元函数声明时遇到了一些问题。
一开始我是这样写的:
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>
的友元函数。
在模板类中友元函数的正确写法是什么?
最佳答案
friend 非模板函数
But the compiler reports a warning that I declare a non-template function.
是的,您在类定义中声明了一个非模板函数。这意味着如果你在类定义之外定义它,你必须将它定义为非模板函数,并且对于所有可能的实例化,比如:
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>&)
是 friend ,其他实例化如 bool operator==(const vector<double>&, const vector<double>&)
不是。
关于c++ - 在模板类中编写友元函数声明的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43696019/