c++ - 模板类和插入提取重载

标签 c++ templates operator-overloading inline insertion

如何在模板类中重载插入 (<<) 和/或提取 (>>) 运算符而不使其内联。我想将 << 或 >> 运算符作为友元类。 我知道如何让它内联 矩阵类中的内联示例

friend ostream& operator<<(ostream& ostr, const Matrix<T>& inputMatrix)
{
   ...
   // create the ostr
   return ostr;
}

但我希望代码位于模板类定义之外。

g++ 告诉我在函数名称后添加 <>,我照做了,但是当我尝试实例化 SOMETYPE 类型的矩阵时,它给了我一个错误,它不知道如何提取或插入该类型。

最佳答案

如果你真的想在外部定义运算符并且只与类型与此模板实例化一致的运算符实例化友好,正确的语法是:

template <typename T> class test; // forward declare template class
template <typename T>              // forward declare the templated operator
std::ostream& operator<<( std::ostream&, test<T> const & );

template <typename T>
class test {                      // define the template
   friend std::ostream& operator<< <T>( std::ostream&, test<T> const & ); // befriend
};
template <typename T>              // define the operator 
std::ostream& operator<<( std::ostream& o, test<T> const & ) {
   return o;
}

在大多数情况下,将定义从类中提取出来是不值得的,因为您仍然需要在标题中提供它,并且需要额外的工作。

另请注意,编译器在查找方面略有不同。在类定义中内联函数的情况下,编译器不会发现该函数除非其中一个参数实际上是模板的类型,因此它有效地降低了可见性和数量编译器必须做的工作(如果模板化的 operator<< 是在类之外定义的,编译器将在它找到 a << b 的所有地方发现它作为重载决议的候选者,只是在所有情况下丢弃它其中第二个参数不是 test<T>(它将在所有错误消息中将模板化运算符显示为候选,因为它无法匹配 operator<<,这已经是一个足够长的列表)。

关于c++ - 模板类和插入提取重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4137494/

相关文章:

c# - 不使用点运算符访问类属性

C# 字符* 到字符串

c++ - 如何使外部可访问的结构内的可变参数模板?

ruby - 如何使值在所有 Liquid 模板中可用

C++ 当模板参数推导失败时

具有不同模板参数值的模板结构的 C++ 访问 protected 成员

c++ - CPU 数量的增加会降低性能,CPU 负载不变并且没有通信

c++ - 现代c++是否会有默认的初始化值

c++ - 初始化静态二维数组

operator-overloading - 重载 opIndexAssign