我想在类中添加一些友元声明。比如我想增加operator==
的一些功能, operator <
.所以我要做的是使用前向声明:
template <typename >
class MyBlob;
template <typename T>
bool operator==(const MyBlob<T> &, const MyBlob<T>&);
template <typename T>
bool operator!=(const MyBlob<T> &, const MyBlob<T>&);
template <typename T>
bool operator<(const MyBlob<T> &, const MyBlob<T>&);
template <typename T>
class MyBlob
{
friend bool operator== <T>(const MyBlob<T> &lhs,const MyBlob<T> &rhs);
friend bool operator!= <T>(const MyBlob<T> &lhs,const MyBlob<T> &rhs);
friend bool operator< <T>(const MyBlob<T> &lhs,const MyBlob<T> &rhs);
//other things
};
这很烦人,我必须使用 template <typename T>
三遍。这确实降低了可读性。
那么,有没有什么方法可以让前向声明更简单呢?或者我可以有一些方法像普通函数一样在一个地方声明这些东西吗?
如果无法完成,正在使用 typedef
简化 template <typename T>
好主意?
最佳答案
您可以尝试在类声明中定义友元运算符:
template <typename T>
class MyBlob {
friend bool operator== (const MyBlob& lhs, const MyBlob& rhs) {
// ...
}
friend bool operator!= (const MyBlob& lhs, const MyBlob& rhs) {
// ...
}
friend bool operator< (const MyBlob& lhs, const MyBlob& rhs) {
// ...
}
// ...
};
关于c++ - C++模板的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50111896/