模板与类型铸造

Template vs type casting

本文关键字:类型      更新时间:2023-10-16

我有基于float的矢量类,我用来存储对象的协调物,当我需要它们作为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;
};