使用 sfml 向量的模板函数重载解决方案

Template Function Overload Resolution with sfml vectors

我正在尝试为 sfml 库的 "sf::Vector2" 模板 类(基本上只包含指定类型的 x 和 y 参数)编写一些运算符。我需要实现关于 "Vector-Vector" 和 "Vector-Scalar/Scalar-Vector" 交互的基本算术运算符。这是我到目前为止所做的一个例子(乘法运算符):

//multiply vectors
template<typename TResult, typename TLeft, typename TRight>
inline auto operator*(const sf::Vector2<TLeft>& lhs, const sf::Vector2<TRight>& rhs){
    return sf::Vector2<TResult>(lhs.x * rhs.x, lhs.y * rhs.y);
}
//multiply sf vector and scalar
template<typename VT, typename ST>
inline auto operator*(const sf::Vector2<VT>& vect, const ST& scalar) {
    return sf::Vector2<VT>(vect.x * scalar, vect.y * scalar);
}
template<typename VT, typename ST>
inline auto operator*(const ST& scalar, const sf::Vector2<VT>& vect) {
    return vect * scalar;
}

问题是当我尝试调用运算符时,例如:

sf::Vector2<int> v1, v2;
sf::Vector2<int> v3 = v1 * v2;

编译器使用了 such 运算符的第二个版本(涉及标量的那个),因此会生成错误。我认为这不会发生,并且由于重载决议,编译器会考虑运算符的第一个版本(该函数接受两个向量而不是一个向量和一个泛型类型)。我有什么不明白的?

在您的向量乘法重载中,无法推导出模板参数 TResult。您可以使用 std::common_type_t:

解决此问题
template<typename TLeft, typename TRight>
inline auto operator*(const sf::Vector2<TLeft>& lhs, const sf::Vector2<TRight>& rhs){
    return sf::Vector2<std::common_type_t<TLeft, TRight>>(lhs.x * rhs.x, lhs.y * rhs.y);
}