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