This is a follow-up to my general question: bit-twiddling-find-next-power-of-two
I have now created the following template function:
template <typename T>
T nextPowerOfTwo(T n)
{
std::size_t k=1;
n--;
do {
n |= n >> k ;
k <<=1;
}
while (k < sizeof(T)*8)
return ++n;
}
2 Questions:
- Specifying T as
unsigned
innextPowerOfTwo(unsigned T n)
threw a compiler error. Can I somehow specifiy T to be unsigned? - Is there something that can be honed elegance or performance-wise?
EDIT: Corrected the code, it was crap in the beginning
EDIT: Corrected the code again. I am really sorry. It was quite obvious actually. But thanks anyway for the hints. I wanted to delete it, but there were already too many contributions.