我有一个基于 float 的 vector 类,我用它来存储我的对象的坐标,当我需要它们作为 int 时,我会简单地进行类型转换。 但有时我发现自己处于一种根本不需要 float 的情况,我可以使用相同的类但基于整数。 那么我应该在这个类上使用模板还是让它基于 float ?
#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;
};
最佳答案
i'm not in need of float at all and I could use the same class but based on integer
是的,使Vec2
成为一个类模板在这里是合适的。这将允许您在任何数字类型上对类进行参数化,同时避免接口(interface)和逻辑的重复。
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;
};
关于c++ - 模板与类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47912115/