模板转换
template conversion
本文关键字:转换 更新时间:2023-10-16
我有两个类int_t
, uint_t
作为有符号类型和无符号类型:
template <typename lo_t> struct uint_t;
template <typename hi_t, typename lo_t>
struct int_t
{
lo_t lo;
hi_t hi;
int_t() : hi(0), lo(0) {}
int_t(int value) : lo(value), hi(value<0? -1: 0) {}
int_t(unsigned value) : lo(value), hi(0) {}
int_t(const uint_t<lo_t>&);
//template<typename ty_a, typename ty_b> int_t(const int_t<ty_a, ty_b>&);
};
template <typename hi_lo>
struct uint_t
{
hi_lo lo, hi;
uint_t() : lo(0), hi(0) {}
uint_t(int value) : lo(value), hi(value<0? -1: 0) {}
uint_t(unsigned value) : lo(value), hi(0) {}
template<typename hi_t>
uint_t(const int_t<hi_t, hi_lo>& value) : hi(value.hi), lo(value.lo) {}
};
template <typename hi_t, typename lo_t>
int_t<hi_t, lo_t>::int_t(const uint_t<lo_t>& value) : hi(value.hi), lo(value.lo)
{}
因为我想让它们像内置类型一样工作,所以我定义了从一个到另一个的转换操作符,所以我可以编写像next这样的代码,并且仍然可以工作:
typedef int_t<int, unsigned> int64;
typedef uint_t<unsigned> uint64;
int64 a = 1000;
uint64 b = a;
uint64 x = 512;
int64 y = x;
现在剩下的唯一问题是从更高或更低精度的int_t
类型转换到另一个,所以我声明了注释的构造函数这样做,但我不知道在里面写什么?
typedef int_t<int, unsigned> int64;
typedef uint_t<unsigned> uint64;
typedef int_t<int64, uint64> int128;
typedef uint_t<uint64> uint128;
int64 a = 1024;
int128 b = a;
int128 x = 100;
int64 y = x;
你必须定义你想让他们做什么。对于无符号,增加大小很容易,您只需将高位设置为0,并从操作数复制低位。对于有符号的操作数,您可能希望对其进行符号扩展。
对于收缩,你还必须决定你想做什么。如果值不合适,是否要抛出?最有可能的是,你只是想扔掉所有的高阶位,并将其存储在可用的空间中。
我找到了小端和大端的答案:
template<typename ty_a, typename ty_b>
int_t(const int_t<ty_a, ty_b>& value)
{
*this = value < 0? -1: 0;
#ifdef BIG_ENDIAN
if (sizeof(*this) < sizeof(value))
*this = *((int_t*)&value.lo + (sizeof(value.lo)/sizeof(*this) - 1));
else
*((int_t<ty_a, ty_b>*)&hi + sizeof(*this)/sizeof(value) - 1) = value;
#else
if (sizeof(*this) < sizeof(value))
*this = *(int_t*)&value;
else
*(int_t<ty_a, ty_b>*)&lo = value;
#endif
}
记住答案要求operator==
和operator<
为int_t
定义
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中使用nlohmann从类到json的转换
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 复制列表初始化的隐式转换的等级是多少
- 正在将指针转换为范围
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 是否可以从int转换为enum类类型
- 了解 GLM- openGL 中的相机转换
- 将无符号char*转换为std::istream*C++