unsigned shift template in C++
I'd like to do an unsigned shift in C++. Here's my example code. The problem with it is it isn't generic. This code is completely wrong. It will not work on longs and it wont work on smaller types like char. I tried (unsigned T)
but that is a syntax error. How might i make this generic without specialization?
#include <cassert>
template<class T>
T unsigned_shift(const T&t, int s) { return ((unsigned int)t)>>s; }
int main()
{
assert(unsigned_shift(-1, 2)==(-1u>>2));
assert(unsigned_shift((char)-1, 2)==开发者_C百科64);
}
If you can use Boost, the type_traits library has the make_unsigned
template that would fit your needs perfectly.
#include <boost/type_traits/make_unsigned.hpp>
template<class T>
T unsigned_shift(const T&t, unsigned int s)
{
return ((make_unsigned<T>::type)t)>>s;
}
(I changed the type of s
to unsigned int
because the operation of the shift operators is undefined for negative values of the second operand - see §5.8 ¶1)
What about casting to unsigned long
to do the shift and then casting back to T
to return it?
Also in a normal twos complement wouldn't the result of the second shift would be 63 not 64?
精彩评论