我有一个带有友元函数的 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/