Define new operator in c++

Viewed 150

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.

1 Answers

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;
}
Related