重载类模板的非成员算术

Overloading non-member arithmetic for class templates

本文关键字:成员 重载      更新时间:2023-10-16

我正在尝试重载运算符*以处理使用不同类型的实例化的类模板,但从编译器获得"模板参数列表过多"。这是我的函数实现:

template <typename T>
template <typename E>
inline Vec2<T> operator*(Vec2<T> lhs, Vec2<E>& rhs)
{
   lhs *= rhs;
   return lhs;
}
template <typename T>
template <typename E>
inline Vec2<T> operator*(Vec2<T> lhs, E scalar)
{
    lhs.x *= scalar;
    lhs.y *= scalar;
    return lhs;
}

这是我使用它的用例:

Vec2<float> scale(0.5, 0.8);
Vec2<short> value(50, 100);
Vec2<short> result = value * scale;
// value should now equal (25, 80)

好吧,您使用的语法不正确。

template <typename T>
template <typename E>
//...

仅在定义模板类的模板成员时使用,但情况并非如此。在您的情况下,您应该简单地使用

template <typename T, typename E> Vec2<T> operator*(Vec2<T> lhs, Vec2<E>& rhs)