c++ - 从 Stroustrup 的 C++ 编译模板友元示例时出现问题

标签 c++ templates friend

有谁知道为什么不能编译以及如何纠正它?我正在尝试使用 friend 和模板。我使用的是 Stroustrup C++ 第 4 版第 682-683 页中的代码。

谢谢

#include <iostream>
using namespace std;

template<typename T>
class Matrix;

template<typename T>
class Vector
{
    T v[4];
public:
    friend Vector operator*<>(const Matrix<T>&, const Vector&);
};

template<typename T>
class Matrix 
{
    Vector<T> v[4];
public:
    friend Vector<T> operator*<>(const Matrix&, const Vector<T>&);
};

template<typename T>
Vector<T> operator*(const Matrix<T>& m, const Vector<T>& v)
{
    Vector<T> r;
}

int main(int argc, char *argv[])
{
}

编译:

clang++ -std=c++11 -pedantic -Wall -g test165.cc && ./a.out
test165.cc:12:19: error: friends can only be classes or functions
    friend Vector operator*<>(const Matrix<T>&, const Vector&);
                  ^
test165.cc:12:28: error: expected ';' at end of declaration list
    friend Vector operator*<>(const Matrix<T>&, const Vector&);
                           ^
                           ;
test165.cc:19:22: error: friends can only be classes or functions
    friend Vector<T> operator*<>(const Matrix&, const Vector<T>&);
                     ^
test165.cc:19:31: error: expected ';' at end of declaration list
    friend Vector<T> operator*<>(const Matrix&, const Vector<T>&);
                              ^

最佳答案

友元声明指的是模板operator*的实例化(即 operator*<T> ),但模板不存在(尚未声明),然后导致错误。

需要提前声明算子模板。

例如

template<typename T>
class Matrix;

template<typename T>
class Vector;

// declaration
template<typename T>
Vector<T> operator*(const Matrix<T>& m, const Vector<T>& v);

template<typename T>
class Vector
{
    T v[4];
public:
    friend Vector operator*<>(const Matrix<T>&, const Vector&);
};

template<typename T>
class Matrix 
{
    Vector<T> v[4];
public:
    friend Vector<T> operator*<>(const Matrix&, const Vector<T>&);
};

// definition
template<typename T>
Vector<T> operator*(const Matrix<T>& m, const Vector<T>& v)
{
    Vector<T> r;
}

关于c++ - 从 Stroustrup 的 C++ 编译模板友元示例时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62668815/

相关文章:

c++ - 将不同的模板类存储在同一个容器中

c++ - 推导(非类型)模板参数类型的编译器方差

c++ - 对于具有两个模板变量的模板类,一个变量可以引用另一个变量吗?

c++ - friend 和成员二元运算符的消歧

c++ - 如何与模板化类的构造函数成为 friend ?

c++ - 使用 C++ 代码从 FORTRAN DLL 调用函数

c++ - WASAPI:为独占输出选择波形格式

c++ - 尝试在 Ubuntu Linux 中构建全局键盘 Hook 时出错

c++ - 如何将 vector 插入到特定位置的另一个 vector 中,这样我将同时获得这两个 vector 的大 vector ,并且该位置将被覆盖?

c++ - 嵌套名称说明符中的类型名称不完整