我有两个类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)
{}
Run Code Online (Sandbox Code Playgroud)
因为我希望它们像内置类型一样工作,所以我将转换运算符从一个定义到另一个,这样我就可以像下一个一样编写代码并且仍然有效:
typedef int_t<int, unsigned> int64;
typedef uint_t<unsigned> uint64;
int64 a = 1000;
uint64 b = a;
uint64 x = 512;
int64 y = x;
Run Code Online (Sandbox Code Playgroud)
现在唯一的问题是从更高或更低的精度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;
Run Code Online (Sandbox Code Playgroud)
我想出了小端和大端的答案:
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
}
Run Code Online (Sandbox Code Playgroud)
记住所需的答案operator==
并operator<
为其定义int_t