我有这个基于float的vector类,我用它来存储我的对象的coorinates,当我需要它们作为int时,我只需要进行类型转换。但有时我发现自己处于一种我根本不需要浮动的情况,我可以使用相同的类但基于整数。那么我应该在这个类上使用模板还是应该让它基于浮点数?
#pragma once
class Vec2
{
public:
Vec2(float x, float y);
public:
bool operator==(Vec2& rhs);
Vec2 operator+(Vec2& rhs) const;
Vec2 operator*(float rhs) const;
Vec2 operator-(Vec2& rhs) const;
Vec2& operator+=(Vec2& rhs);
Vec2& operator-=(Vec2& rhs);
Vec2& operator*=(float rhs);
float LenghtSqrt() const;
float Lenght() const;
float Distance(const Vec2& rhs) const;
Vec2 GetNormalized() const;
Vec2& Normalize();
public:
float x, y;
};
我根本不需要浮动,我可以使用相同的类但基于整数
是的,在这里使Vec2
成为一个类模板是合适的。这将允许您在任何数字类型上参数化类,同时避免重复您的接口和逻辑。
template <typename T>
class Vec2
{
public:
Vec2(T x, T y);
public:
bool operator==(Vec2& rhs);
Vec2 operator+(Vec2& rhs) const;
Vec2 operator*(T rhs) const;
Vec2 operator-(Vec2& rhs) const;
Vec2& operator+=(Vec2& rhs);
Vec2& operator-=(Vec2& rhs);
Vec2& operator*=(T rhs);
float LenghtSqrt() const;
float Lenght() const;
float Distance(const Vec2& rhs) const;
Vec2 GetNormalized() const;
Vec2& Normalize();
public:
T x, y;
};