Tworzę klasę Vector2 w C++ jako szablon i chcę zdefiniować operatora +
jako funkcję nie będącą członkiem przyjaciela, który może po prostu dodać dwa wektory.Co ten kod robi i dlaczego go kompiluje?
Jest to deklaracja przyjaciel w moim Vector2 klasy szablonu:
template <class U>
friend Vector2<T> operator+(const Vector2<T> &lhs, const Vector2<T> &rhs);
ten jest zawarty w pliku .hpp
, ale realizacja jest w osobnym .cpp
pliku:
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_);
}
To kompiluje bez wszelkie ostrzeżenia jednak nie wydają się działać.
Vector2<int> v1(4, 3);
Vector2<int> v2(3, 4);
Vector2<int> v3 = v1 + v2;
Kiedy próbuję skompilować powyższy fragment, GCC narzeka:
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]
Co robię źle? Jak poprawnie zdefiniować operatora +
dla mojej klasy szablonu?
"Jest to zawarte w pliku .hpp, ale implementacja jest w osobnym pliku .cpp" ... nawet nie próbuj. Umieść wszystko w nagłówku. http://stackoverflow.com/questions/495021/why-can-templates- only-be-made-in-the-header-file –
Sprawdź ponownie parametry szablonu w deklaracji "friend". Tam jest niedopasowanie. –
T! = U. może wybrać jeden = P – WhozCraig