【问题标题】:Problem compiling a template friend example from Stroustrup's C++从 Stroustrup 的 C++ 编译模板友元示例时出现问题
【发布时间】:2020-07-01 02:37:39
【问题描述】:

有谁知道为什么这不会编译以及如何纠正它?我正在尝试使用朋友和模板。我正在使用 Stroustrup C++ 4th Ed Page 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>&);
                              ^

【问题讨论】:

  • 去掉 是否有效?

标签: c++ templates friend


【解决方案1】:

友元声明引用了模板operator*(即operator*&lt;T&gt;)的实例化,但模板不存在(尚未声明)导致报错。

需要提前声明算子模板。

例如

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多