我有一个带有友元函数的 Matrix 类,可与运算符 << 一起使用。这一切都工作正常,但我现在想要部分专门化该友元函数,以便在 Matrix 类将 Matrix 作为其模板参数时以不同的方式工作(即,当该类的实例已声明为 Matrix> 时)。首先在类定义中我
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);
但这给了我来自编译器的多个声明错误。
我似乎不知道如何实现这一点。
I have a Matrix class with a friend function to use with operator<<. This all works fine but I now want to partially specialize that friend function to work differently if the Matrix class has Matrix as its template parameter (i.e. when the instance of the class has been declared like Matrix< Matrix< char > >). In the class definition first I had
template <typename U>
friend std::ostream& operator<<(std::ostream& output, const Matrix<U>& other);
and I tried adding
friend std::ostream& operator<<(std::ostream& output, const Matrix<Matrix<char> >& other);
but this gave me multiple declaration errors from the compiler.
I can't seem to figure out how to accomplish this.
发布评论
评论(2)
不存在函数模板的部分特化。
你需要重载,而不是专业化。这应该可以干净地编译、链接和运行(对我来说就是如此):
如果您从中收到编译器错误,则您可能有一个有错误的编译器。
There's no such thing as a partial specialization of a function template.
You need overloading, not specialization. This should compile, link, and run cleanly (it does for me):
If you are getting compiler errors from this, you probably have a buggy compiler.
尝试明确地编写专业化:
Try writing the specialization explicitly: