5

+テンプレートとして C++ で Vector2 クラスを作成しています。演算子を、単純に 2 つのベクトルを追加できる非メンバーのフレンド関数として定義したいと考えています。

これは、Vector2 テンプレート クラス内のフレンド宣言です。

template <class U>
friend Vector2<T> operator+(const Vector2<T> &lhs, const Vector2<T> &rhs);

これは.hppファイルに含まれていますが、実装は別の.cppファイルにあります。

template <class T>
Vector2<T> operator+(const Vector2<T> &lhs, const Vector2<T> &rhs)
{
    return Vector2<T>(lhs.x_ + rhs.x_, lhs.y_ + rhs.y_);
}

これは警告なしでコンパイルされますが、動作していないようです。

Vector2<int> v1(4, 3);
Vector2<int> v2(3, 4);

Vector2<int> v3 = v1 + v2;

上記のスニペットをコンパイルしようとすると、GCC は不平を言います:

prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:26:28: error: no match for ‘operator+’ in ‘v1 + v2’

source/vector2.hpp:31:23: note: template<class U> Vector2<int> operator+(const Vector2<int>&, const Vector2<int>&)
source/vector2.hpp:31:23: note:   template argument deduction/substitution failed:
prog.cpp:26:28: note:   couldn't deduce template parameter ‘U’
prog.cpp:26:18: warning: unused variable ‘v3’ [-Wunused-variable]

私は何を間違っていますか?+テンプレート クラスの演算子を正しく定義するにはどうすればよいですか?

4

2 に答える 2

5

コンパイラは、問題が何であるかを明確に示しています。テンプレート パラメーター 'U' を推測できません。あなたの宣言 (.hpp ファイル) が間違っています。する必要があります

template <class T>
friend Vector2<T> operator+(const Vector2<T> &lhs, const Vector2<T> &rhs);
于 2013-01-14T11:57:32.090 に答える
3

オペレーターのテンプレートは、U使用されていないパラメーターを使用します。シグニチャはT代わりに使用します。これはおそらく周囲のクラステンプレートからのものです。

template <class U>
friend Vector2<T> operator+(const Vector2<T> &lhs, const Vector2<T> &rhs);

は使用されていないためU、コンパイラはそれがどのタイプであるかを自動的に推測できず、エラーが発生します。

テンプレートパラメータを一貫して使用し、テンプレートの定義を.hppファイルに入れれば、問題はありません。

于 2013-01-14T12:00:47.877 に答える