1

I want to redefine the bit shift operator on a 64 bit unsigned integer in c++ in such a way that I can do say, x<<d, where x is a 64 bit integer and d is an integer with |d|<64, to make it equivalent to x<<d for d>0 and x>>|d| for d<0.

The only way I know how to do this is to define a whole new class and overload the << operator, but I think that also means I need to overload all the other operators I need (unless there is a trick I don't know), which seems a bit silly considering I want them to behave exactly as they do for the pre-defined type. It's just the bitshift that I want to change. At present, I have just written a function called 'shift' to do this, which doesn't seem very c++ ish, even though it works fine.

What is the stylistically correct way to do what I need?

Thanks

2 Answers 2

5

If you were able to do this, it would be very confusing to other C++ programmers who read your code and see:

int64 x = 92134;
int64 y = x >> 3;

And have it behave differently than their expectations, and behave differently from what the C++ standard defines.

The stylistic choice that agrees most with the C++ code I've seen is to continue using your own myshift() function.

int64 y = myshift(x, 3);
1
0

I think it's very horrible (and I propose it just for fun) but... if you accept to wrap the number of bit shifted in a struct...

#include <iostream>

struct foo
 { int num; };

long long int  operator<< (const long long int & lli, const foo & f)
 {
   int d { f.num };

   if ( d < 0 )
      d = -d;

   if ( d >= 64 )
      d = 0;

   return lli << d;
 }

int main()
 {
   long long int  lli { 1 };

   std::cout << (lli << foo{+3}) << std::endl;   // shift +3
   std::cout << (lli << foo{-3}) << std::endl;   // shift +3 (-3 -> +3)
   std::cout << (lli << foo{+90}) << std::endl;  // no shift (over 64)
   std::cout << (lli << foo{-90}) << std::endl;  // no shift (over 64)

   return 0;
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.