爲什麼不把X,unsigned char型和投它?你當然不需要移動超過255位?
const unsigned char x = static_cast<unsigned char>(A - B);
或者可能使用掩蔽,以確保轉變是在這樣的範圍:
const unsigned int x = static_cast<unsigned int>(A - B) & 0x1f; // limit A-B to have a range of (0 - 31)
編輯:
響應這裏的評論是一個想法:
template<unsigned int A, unsigned int B>
int foo() {
int v = 1;
const int x = A - B;
if (x > 0) {
v = v << (static_cast<unsigned int>(x) & 0x1f);
}
bar(v);
}
注意:你可以用類似的東西代替0x1f:(CHAR_BIT * sizeof(T) - 1)
編輯:響應最新的評論,這個代碼不發出任何警告與編譯:G ++ -W -Wall -ansi -pedantic test.cc -o測試
#include <iostream>
template<unsigned int A, unsigned int B>
int foo() {
int v = 1;
const int x = A - B;
if (x > 0) {
v = v << (static_cast<unsigned int>(x) & 0x1f);
}
return v;
}
int main() {
std::cout << foo<1, 3>() << std::endl;
std::cout << foo<3, 1>() << std::endl;
std::cout << foo<300, 1>() << std::endl;
std::cout << foo<25, 31>() << std::endl;
}
更具體:我有'A == 25 `和`B == 31`。這給了我`x == -6`看起來像`111 ... 11010`並截斷它仍然會給我一個相當大的數字 – 2008-11-06 00:34:21