c++ - C++模板的前向声明

标签 c++ templates

我想在类中添加一些友元声明。比如我想增加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/

相关文章:

c++ - 不允许类型名称

c++ - 编译报错opencv

c++ - 填充数组会导致数组周围的堆栈被破坏

c++ - 为什么值初始化如此命名?

templates - Lua:将上下文传递到加载字符串中?

c++ - 模板化函数只接受右值

c++ - 在boost中为斐波那契堆定义比较函数

c++ - 类型嵌套在模板类中的部分特化

c++ - 我如何编码类似std::variant的开关?

c++ - 如何删除 QT 项目文件中的重复代码?