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)==64);
}
If you can use Boost, the type_traits library has the
make_unsignedtemplate that would fit your needs perfectly.(I changed the type of
stounsigned intbecause the operation of the shift operators is undefined for negative values of the second operand – see §5.8 ¶1)