我一直试图从“The C ++ Programming Language(4th Edition)”一节“23.4.7 Friends”中获得以下代码,但是无法成功。
template<typename T> class Matrix;
template<typename T>
class Vector {
T v[4];
public:
friend Vector operator*<>(const Matrix<T>&, const Vector&); /* line 7 */
// ...
};
template<typename T>
class Matrix {
Vector<T> v[4];
public:
friend Vector<T> operator*<>(const Matrix&, const Vector<T>&); /* line 14 */
// ...
};
template<typename T>
Vector<T> operator*(const Matrix<T>& m, const Vector<T>& v)
{
Vector<T> r;
// ... m.v[i] and v.v[i] for direct access to elements ...
return r;
}
以下是上述API的示例用法:
int main() {
Matrix<int> lhs;
Vector<int> rhs;
Vector<int> r = lhs * rhs;
return 0;
}
g ++ with version:
g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3
给出了以下输出:
test.cpp:7: error: declaration of ‘operator*’ as non-function
test.cpp:7: error: expected ‘;’ before ‘<’ token
test.cpp:14: error: declaration of ‘operator*’ as non-function
test.cpp:14: error: expected ‘;’ before ‘<’ token
并与版本铿锵:
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.0.0
Thread model: posix
给出了以下输出:
test2.cpp:7:19: error: friends can only be classes or functions
friend Vector operator*<>(const Matrix<T>&, const Vector&);
^
test2.cpp:7:28: error: expected ';' at end of declaration list
friend Vector operator*<>(const Matrix<T>&, const Vector&);
^
;
test2.cpp:14:22: error: friends can only be classes or functions
friend Vector<T> operator*<>(const Matrix&, const Vector<T>&);
^
test2.cpp:14:31: error: expected ';' at end of declaration list
friend Vector<T> operator*<>(const Matrix&, const Vector<T>&);
^
;
4 errors generated.
这本书说:
&lt;&gt;在需要firend函数的名称后才能说清楚 朋友是模板功能。
我无法在代码中发现问题,是吗?
答案 0 :(得分:2)
是的,这是书中的一个错误。
此时必须已显示功能模板,否则为it cannot be instantiated to produce the overload you're trying to befriend。
因此,将运算符定义移到Vector
之上(这本身就要求我们提供前向声明)solves the problem。