在模板类中编写朋友函数声明的正确方法是什么?
What is the right way to write friend function declarations in template 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>
的朋友函数。
在模板类中编写朋友功能的正确方法是什么?
朋友非网板函数
,但编译器报告了我声明非模板功能的警告。
是的,您正在宣布类定义中的非模板函数。这意味着,如果您将其定义为类定义,则必须将其定义为非模板函数,并且对于所有可能的实例,例如:
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
相关文章:
- 声明高维向量的更简洁的方法
- 模板方法访问正向声明的类仅在没有此指针的情况下无法编译
- 将子类方法声明为基类的友元
- 如何在声明为 const 的方法中更改类成员
- 编译器无法识别在类声明之外定义的方法
- 在类中声明 Array 成员的正确方法
- 如何在该接收类之外声明嵌套类的方法
- 转发声明在命名空间中不起作用的替代方法
- 在实现文件中使用模板参数声明方法
- 为什么在主方法之前声明方法会产生错误 c++
- 在 cpp 正文中声明方法时未定义的符号
- 声明方法时没有名称空间,也没有对C 作用的方法的对象
- 无法在类中声明方法 (C++_
- 可变声明方法
- 为什么这种前向声明方法会产生错误
- 在c++中可以通过模板声明方法吗?
- 在c++中声明方法时= 0的含义是什么?
- 为什么我需要为部分模板专门化重新声明方法/成员?
- 两种数组声明方法的区别
- 强制编译器声明方法是否已被实现- c++