流运算符的 C++ 部分模板特化

标签 c++ template-specialization ostream friend-function

我有一个带有友元函数的 Matrix 类,可以与运算符<<一起使用。这一切工作正常,但我现在想部分专门化该友元函数,以便在 Matrix 类将 Matrix 作为其模板参数时以不同方式工作(即,当类的实例已被声明为 Matrix< Matrix< char >>)。在类定义中我首先有

template <typename U>
friend std::ostream& operator<<(std::ostream& output, const Matrix<U>& other);

我尝试添加

friend std::ostream& operator<<(std::ostream& output, const Matrix<Matrix<char> >& other);

但这给了我多个来自编译器的声明错误。 我似乎无法弄清楚如何做到这一点。

最佳答案

There's no such thing as a partial specialization of a function template .

您需要重载,而不是专门化。这应该可以干净地编译、链接和运行(对我来说是这样):

#include <iostream>

template <typename T>
class Matrix {
  public:
    template <typename U> friend std::ostream& 
        operator<<(std::ostream& output, const Matrix<U>& other);
    friend std::ostream& 
        operator<<(std::ostream& output, const Matrix<Matrix<char> >& other);    
};


template <typename U>
std::ostream& 
operator<<(std::ostream& output, const Matrix<U>& other)
{
    output << "generic\n";
    return output;
}

std::ostream& 
operator<<(std::ostream& output, const Matrix<Matrix<char> >& other)
{
    output << "overloaded\n";
    return output;
}

int main ()
{
    Matrix<int> a;
    std::cout << a;

    Matrix<Matrix<char> > b;
    std::cout << b;
}

如果你从这里得到编译器错误,你可能有一个错误的编译器。

关于流运算符的 C++ 部分模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7860386/

相关文章:

c++ - 想要使用 STL 在 C++ 中扫描二维数组

c++ - powerOf(int x, int n) 的最佳方式?

c++ - 我如何从 wostream 转换为 ostream

c++ - 如何使用运算符<<获取在ostream中写入了多少个字符?或者如何阅读所写的内容?

C++ ostream格式化

android - JNI OpenCV Android 画线或矩形功能

c++ - C++中的方法链接?

c# - 两种可能的编程模式,哪一种更合适?

C++ 专门针对特定类型的 lambda

c++ - 为 STL 容器专门化成员函数