User-defined operators in C++

Правка ru1, от 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;
}

Теги #c++

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский bogorodniy 2020-08-10 22:51:24 1375 Initial revision for English translation
ru1 Русский bogorodniy 2020-08-10 22:44:25 1375 Первая редакция (опубликовано)