Friday, December 9, 2011

Инфиксная запись функций (С++)

В общем-то, последующее — полный изврат и к применению не рекомендуется :)


#include <functional>

template <typename Func> struct infix_operator;
template <typename Func> infix_operator<Func>& operator|(int, infix_operator<Func>&);
template <typename Func> int operator|(const infix_operator<Func>&, int );

template <typename Func>
struct infix_operator {
    typedef infix_operator<Func> infix_t;
    int left;
    static Func func;
    friend infix_t& operator|<>(int, infix_t&);
    friend int operator|<>(const infix_t&, int);
};
template <typename Func> Func infix_operator<Func>::func;

template <typename Func>
infix_operator<Func>& operator|(int left, infix_operator<Func>& op) {
    op.left = left; return op;
}

template <typename Func>
int operator|(const infix_operator<Func>& op, int right) {
    return infix_operator<Func>::func(op.left, right);
}

static struct : infix_operator<std::plus<int>> {} PLUS;
static struct : infix_operator<std::multiplies<int>> {} TIMES;
static struct : infix_operator<std::divides<int>> {} DIV;
static struct : infix_operator<std::modulus<int>> {} MOD;

#include <iostream>
int main() {
    std::cout << (((2 |PLUS| 3) |TIMES| (36 |DIV| 6)) |MOD| 17) << std::endl;
}