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;
}
wow thx, it is very useful!!
Auto comment: topic has been translated by bogorodniy (original revision, translated revision, compare)
very cool!
Some time ago I wrote
Pretty useless although :)
Interesting idea, execution leaves much to be desired.
1) You shouldn't put
int&
as the parameter type foroperator>>
,int
will do just fine. In fact, you'll get compilation errors if you try to use an r-value as an operand, as in the example below.2) After replacing
int&
withint
, what does this print?I made it a bit shorter (and also without bug, which ivan100sic mentioned)
And this can be improved to work with any type:
Actually, it is better to use
operator ,
, instead ofoperator ^
to avoid extra brackets (link)By the way, my code creates structure on each
minEqual
, so probably it is slower than the original version, but I am not sure. However, if you aim for speed, you shouldn't use any of these options, I think.You should
return x
in the first function ;)With
-O2
, the compiler will even get rid of all function calls, you can try it on godbolt.orgI suppose that I write
x minEqual f(1, 2, 3);
to minimizex
by a result of function callf(1, 2, 3)
. Obviously it 1) will not compile and 2) might lead to undefined behavior iff(int, int, int)
uses minEqual operator as well.So that I just return to simpler alternative:
An I use
And I use normal functions like these