Will neeh
Will neeh

Reputation: 49

Template vs type casting

I have this vector class based on float that I use to store the coorinates of my objects and when i need them as an int I would simply do type casting. But sometimes i find myself in a situation where i'm not in need of float at all and I could use the same class but based on integer. So should i use a template on this class or should i let it be float based?

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

};

Upvotes: 0

Views: 264

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93264

i'm not in need of float at all and I could use the same class but based on integer

Yes, making Vec2 a class template is appropriate here. This would allow you to parametrize the class on any numerical type, while avoiding duplication of your interface and logic.

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

Upvotes: 2

Related Questions