Skip to content

Instantly share code, notes, and snippets.

@madbence
Last active May 23, 2023 17:35
Show Gist options
  • Save madbence/5639239 to your computer and use it in GitHub Desktop.
Save madbence/5639239 to your computer and use it in GitHub Desktop.
Infix operators in C++ :o
#include <iostream>
using namespace std;
template<class T>
struct Bind {
T first;
T (*fun)(const T&, const T&);
Bind(T (*fun)(const T&, const T&), T f):first(f), fun(fun){}
T operator()(const T& o) { return fun(first, o); }
};
template<class T>
struct Infix {
T (*fun)(const T&, const T&);
Infix(T (*fun)(const T&, const T&)):fun(fun){}
};
template<class T>
struct Infix2 {
Bind<T> fun;
Infix2(const Bind<T>& f):fun(f){}
T operator|(const T& t) { return fun(t); }
};
template<class T>
Infix2<T> operator|(const T& t, const Infix<T>& op) {
return Infix2<T>(Bind<T>(op.fun, t));
}
int mul(const int& a, const int& b) { return a*b; }
int main()
{
Infix<int> x(mul);
cout << (2 |x| 2) << endl; //4
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment