User-defined operators in C++

Revision ru1, by bogorodniy, 2020-08-10 22:44:25

I wondered for a long time how to make different user-operators. For example write this x minEqual y instead of x = min(x, y)

So recently I've done this, and decided to share it with you.

#include <bits/stdc++.h>

using namespace std;
struct mineq_operator
{
    int tempVal=1000;
    inline mineq_operator operator<<(int& x)
    {
        this->tempVal = x;
        return *this;
    } inline mineq_operator operator>>(int& x)
    {
        x = min(x, tempVal);
        return *this;
    }
};
mineq_operator __me;
inline void operator<<(int& x, mineq_operator& b)
{
    b.tempVal = x;
}
#define minEqual <<__me;__me>>
signed main()
{
    int x = 3, y = 2;
    y minEqual x;
    cout << x << ' ' << y << endl;
}

For use it like x = min(x, y); just write y minEqual x;

And this in compressed format:

#include <bits/stdc++.h>

using namespace std;
struct mineq_operator {int tempVal=1000;inline mineq_operator operator<<(int& x) {this->tempVal = x;return *this;}inline mineq_operator operator>>(int& x) {x = min(x, tempVal);return *this;}};
mineq_operator __me; inline void operator<<(int& x, mineq_operator& b) {b.tempVal = x;}
#define minEqual <<__me;__me>>
signed main() {
  int x = 3, y = 2;
    y minEqual x;
    cout << x << ' ' << y << endl;
}

Tags #c++

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English bogorodniy 2020-08-10 22:51:24 1375 Initial revision for English translation
ru1 Russian bogorodniy 2020-08-10 22:44:25 1375 Первая редакция (опубликовано)