2011-08-11 48 views
5

我有兩個類int_tuint_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) 
{} 

因爲我希望他們的工作就像內置類型我從一個到另一個定義轉換操作符,所以我可以寫像未來仍然代碼工作:

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; 

回答

1

我想通了小和大Endians答案:

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

1

你必須定義你希望他們做什麼。對於無符號數,增加的大小很容易,只需將高位設置爲0並從操作數複製低位。對於簽名,您可能希望簽名擴展操作數。

對於縮小,你也必須決定你想要做什麼。如果價值不合適,你想拋出嗎?很可能你只是想扔掉所有的高位並將其存儲在可用空間中。

+0

這就是excatly定義我想要什麼,但怎麼樣?一個exmaple會很好。 –