模板与类型铸造
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;
};
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 类中的字符串不命名类型