Bawiłem się przed chwilą operatorami i wpadłem na ciekawy pomysł, aby zrealizować coś takiego, żeby możliwe było zapisanie kodu w ten sposób i działał on poprawnie:
#include <iostream>
#include "mojeoperatory.h"
int _silnia(int n)
{
int wynik = 1;
for (int i=1; i<=n; i++)
wynik*=i;
return wynik;
}
int _kwadrat(int n)
{
return n*n;
}
int _potega(int a, int b)
{
int c = 1;
for (int i=0; i<b; i++)
c*=a;
return c;
}
#define silnia zprawej(int,_silnia)
#define kwadrat zlewej(int,_kwadrat)
#define potega zobu(int,_potega)
using namespace std;
int main()
{
int s = 5 silnia;
int k = kwadrat 3;
int p = 2 potega 3;
cout << s << endl;
cout << k << endl;
cout << p << endl;
return 0;
}
i udało mi się :P
oto jak wygląda "magiczny" plik mojeoperatory.h:
template<class T>
struct __tmp1__
{
__tmp1__(T (*f)(T)): f(f) {}
T (*f)(T);
T operator()(T a) { return f(a); }
};
template<class T>
struct __tmp2__
{
__tmp2__(T (*f)(T,T)): f(f) {}
T b;
T (*f)(T,T);
T operator()(T a) { return f(a,b); }
};
template<class T>
T operator>> (T a, __tmp1__<T> __tmp1__)
{
return __tmp1__(a);
}
template<class T>
T operator<< (__tmp1__<T> __tmp1__, T a)
{
return __tmp1__(a);
}
template<class T>
T operator>> (T a, __tmp2__<T> __tmp1__)
{
return __tmp1__(a);
}
template<class T>
__tmp2__<T> operator<< (__tmp2__<T> __tmp1__, T a)
{
__tmp1__.b = a;
return __tmp1__;
}
#define zprawej(typ,funkcja) >> __tmp1__<typ>(funkcja)
#define zlewej(typ,funkcja) __tmp1__<typ>(funkcja) <<
#define zobu(typ,funkcja) >> __tmp2__<typ>(funkcja) <<
nie jest to może zbyt skomplikowane, ale zastosowanie wydaje mi się dość ciekawe :P