【问题标题】:Template Function Overload Resolution with sfml vectors使用 sfml 向量的模板函数重载解决方案
【发布时间】:2017-05-19 22:14:20
【问题描述】:

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

//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;

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

【问题讨论】:

    标签: c++ templates operator-overloading sfml


    【解决方案1】:

    在向量乘法重载中,模板参数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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      • 2019-04-09
      • 2012-10-25
      相关资源
      最近更新 更多