c++ - 模板与类型转换

标签 c++ templates casting type-conversion

我有一个基于 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/

相关文章:

c++ - 如何安全地删除 ATL DLL 中的 std::thread

c++ - 通过分配c内存错误捕获c++异常

c++ - 在编译时区分char和wchar_t

casting - Go:将 map[string]interface{} 转换为 map[string]string 的类型失败

mysql - 在 mysql MEMORY/HEAP 表中允许 TEXT 列的变通方法

java - 是什么导致了 "Incompatible operand types"错误?

c++ - 从0到7生成8个唯一的随机数

javascript - AngularJS 将变量分配给 View 的范围

c++ - c++ 模板会使程序变慢吗?

c++ - 优化标准迭代算法