3

Can we define our own operator in c++?

I need to define a%%b as (a%b+b)%b because sometimes a%b gives a negative value(-239%5=-4), and I want the positive reminder. So if a%b is negative, add b to a%b and return the value. This can be simply done using (a%b+b)%b. I tried

#define a%%b (a%b+b)%b

but it is giving error. We can do this by using a function

int mod(int a, int b){
    return (a%b+b)%b;
}

but I want to do this by defining as I do for a 'for' loop

#define f(i,a,b) for(int i=a;i<b;i++)

please suggest me a way to define a%%b as (a%b+b)%b.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Abhishek Patil
  • 502
  • 1
  • 4
  • 12

1 Answers1

1

You can only overload an existing operator. However, you could wrap an int with your own class, and overload operator% for this class. Like this:

#include <iostream>

struct int_wrapper {
    explicit int_wrapper(int n) : n_(n)
    { }
    operator int() const {
        return n_;
    }
private:
    int n_;
};

int operator%(int_wrapper lhs, int_wrapper rhs) {
    return ((int)lhs % rhs + rhs) % rhs;
}

int main() {
    std::cout << (int_wrapper(-239) % int_wrapper(5)) << std::endl;
}
Igor R.
  • 14,716
  • 2
  • 49
  • 83
  • That's confusing. You have an object that appears to be an `int` (from its name) but has an overloaded '%' operator that behaves similar but different then the build in operator for '%' int – bolov May 07 '20 at 05:55
  • 2
    @bolov I agree. The name should be something like int_with_non_negative_mod. "Ugly notation for an ugly operation", as Stroustrup said :-). – Igor R. May 07 '20 at 07:04