我试图编写自己的向量模板类,但在编写朋友函数声明时遇到了一些问题。
一开始我这样写:
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>的朋友函数。
在模板类中编写朋友函数的正确方法是什么?
发布于 2017-04-29 13:16:50
朋友非模板函数
但是编译器报告了一个警告,我声明了一个非模板函数。
是的,您在类定义中声明了一个非模板函数。这意味着,如果在类定义之外定义它,则必须将其定义为非模板函数,对于所有可能的实例化,如:
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>&) )则不是。
活着
https://stackoverflow.com/questions/43696019
复制相似问题