標題有點難想 , 見諒 , 小細節的問題也有點多 , 請海函。
首先我寫了份 bitwise - bitcount 函式 , 做成 template
最初版是寫成這樣
template<typename T> inline
size_t bitcount(T v) // slow but generation
{
size_t c ;
for(c = 0 ; v &= v - 1; ++c) ;
return c;
}
鑑於效能 , 接著對每種 pod type 做特偏化
template<> inline size_t bitcount(unsigned char v) {}
template<> inline size_t bitcount(unsigned short v) {}
template<> inline size_t bitcount(unsigned int v) {}
template<> inline size_t bitcount(unsigned long v) {}
template<> inline size_t bitcount(unsigned long long v) {}
接著我再回到最原始版的 template , 打算根據 bytes 數去呼叫不同版本的 bitcount
同時想考慮可能有超過 8 bytes 的情況 , 像是 non-padding struct 或 array
可能會用到
template<typename T> inline
size_t bitcount(T v)
{
size_t icount = 0;
switch( size_t ibytes = sizeof(T) )
{
case 8 : return bitcount<unsigned char > (v) ;
case 4 : return bitcount<unsigned int > (v) ;
case 2 : return bitcount<unsigned short> (v) ;
case 1 : return bitcount<unsigned long long> (v) ;
default :
// 一次處理 4 bytes
unsigned int * puint = (unsigned *) & v;
for(size_t itimes = 0 ; itimes < ibytes / 4 ; ++itimes)
icount+=bitcount<unsigned int>( * puint ++);
// 剩下沒處理完的逐一 byte 處理
unsigned char * pchar = (unsigned char *) puint ;
for(size_t itimes = 0; itimes < ibytes % 4 ; ++itimes)
icount+=bitcount<unsigned char>( *pchar++);
}
return icount ;
}
東西是做出來了沒錯,但截至目前為止有幾個問題想請教。
1. 資料型態問題
先拿另一份 code 來講
template<typename T>
T mask_low_nbits(T v , int n)
{
T msk = (1 << n) - 1 ; // 這個有問題
return v & msk ;
}
(1.1) 上面這段在 unsigned long long 時會出包,一般這情況會怎寫?
T v = (1ULL << n) - 1 ;
T v = (static_cast<T>(1) << n) - 1 ;
或是有比較建議的方法嗎?
(1.2) 上面的 T , 請問有沒有辦法判斷傳進來的是 unsigned type ?
目前我找不到相關資料說明 (雖然我覺得不太可能辦到)
2. 自動展開
最終的 template<typename T> size_t bitcount(T v) ; 在非特定 bytes
數下,我是用 for loop 展開,想請問有沒有類似以下的想法讓 template
幫我自己展開 ? ( compile error .. )
template<typename T , size_t nbytes = sizeof(T)>
size_t bitcount(T v)
{
if(nbytes > 4) {
return
bitcount<unsigned> ( v )
+ bitcount<unsigned , nbytes-4 > ( *((unsigned*)& v + 1 ) ) ;
}
else if(nbytes) {
return
bitcount<unsigned char> ( v )
+ bitcount<unsigned char , nbytes-1> ( *( (unsigned char*) &v +1));
}
}
3. Resource
(3.1) 另想知道有沒有文章或是書可以教一些這方面的技巧?
(3.2) 我用 VS 寫 template 的時候,發現 keyin source code ,
IDE 在做 template tips 時, " 好像 " 會比較 lag ,
請問是我的心理因素 , 還是也有人會這樣 ?