【问题标题】:Template vs type casting模板与类型转换
【发布时间】:2017-12-20 18:17:38
【问题描述】:

我有这个基于浮点数的向量类,我用它来存储我的对象的坐标,当我需要它们作为 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;

};

【问题讨论】:

  • 您可以提供float 的默认模板参数typedef Vec2<> Vec2,您还可以为Vec2 提供一个通用名称以用于非默认模板类型。

标签: c++ templates casting type-conversion


【解决方案1】:

我根本不需要浮点数,我可以使用相同的类,但基于整数

是的,在这里将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;
};

【讨论】:

    猜你喜欢
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多