bit shift - How to change a typename's signed-ness in template function c++ -


so i've been trying make "looping" bitwise shift in c++ (11) , have got basic code down this:

#include <cstdio> #include <limits> // is_signed #include <limits.h> // char_bit  template<typename t> t rotl(t input, unsigned int shift) {     return (input<<shift)|(input>>(sizeof(t)*char_bit-shift)); }  template<typename t> t rotr(t input, unsigned int shift) {     return (input>>shift)|(input<<(sizeof(t)*char_bit-shift)); }  int main() {     int = -5;      std::printf( "%i\n", i);      = rotl(i, 4); // or other value     std::printf( "%i\n", i);      = rotr(i, 4); // same value above     std::printf( "%i\n", i); } 

this gives me expected behaviour when output looks following:

-5 -1 -1 

because int signed, if code:

i = (int)rotl((unsigned int)i, 4); . . . = (int)rotr((unsigned int)i, 4); 

the output becomes:

-5 -65 -5 

which works want too. can check signed-ness of t using numeric_limits following:

t rotr(t input, unsigned int shift) {     if(std::numeric_limits<t>::is_signed == false){         return ()     }else{         return // problem here     } } 

but can't seem figure out how turn around signed-ness of t, (unsigned t) invalid typenames. how go doing this? prefer not use standard libraries (personal taste really), if there's no plausible way might consider non std options.

as celticminstrel suggested use std::make_unsigned<t>::type

here how:

 template<typename t> t rotl(t input, unsigned int shift) {     typename std::make_unsigned<t>::type ii = static_cast<typename std::make_unsigned<t>::type>(input);      return static_cast<t>((ii<<shift)|(ii>>(sizeof(t)*char_bit-shift))); } 

Comments