Ошибка в разделе «Язык программирования C ++» «23.4.7 Друзья»

0

Я пытаюсь получить следующую работу кода из книги "C++ Язык программирования (4-е издание)" раздел "23.4.7 Друзья", но не удалось.

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++ с версией:

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

и clang с версией:

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.

В книге говорится:

<> После имени функции firend необходимо указать, что друг является функцией шаблона.

Я не мог определить проблему в коде, не так ли?

Теги:
templates
operator-overloading
friend

1 ответ

2
Лучший ответ

Да, это ошибка в книге.

Шаблон функции должен быть уже видимым в этой точке, иначе он не может быть создан для создания перегрузки, которую вы пытаетесь подружиться.

Таким образом, перенос операторных определений выше, чем Vector (который сам по себе требует, чтобы мы предоставляли форвардную декларацию) решает проблему.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню