Created
September 15, 2016 21:19
-
-
Save bkietz/7dc3df59c13dc90d3fa5244b43d45bfd to your computer and use it in GitHub Desktop.
Operator overload playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <type_traits> | |
template <typename T> | |
struct is_expression : std::false_type {}; | |
template <typename T, typename R = T> | |
using expression_enable = typename std::enable_if< | |
is_expression<T>::value, R | |
>::type; | |
struct identifier_expression | |
{ | |
char const *name; | |
void print(std::ostream &os) { os << name; } | |
}; | |
template <> | |
struct is_expression<identifier_expression> : std::true_type {}; | |
template <typename L, typename R, typename Op> | |
struct binary_expression | |
{ | |
L l; | |
R r; | |
Op op; | |
void print(std::ostream &os) | |
{ | |
// TODO: precedence | |
os << "("; | |
l.print(os); | |
op.print(os); | |
r.print(os); | |
os << ")"; | |
} | |
}; | |
template <typename L, typename R, typename Op> | |
struct is_expression<binary_expression<L, R, Op>> : std::true_type {}; | |
#define BINARY_OPERATOR(OPCHARS, OPNAME) \ | |
struct OPNAME \ | |
{ \ | |
void print(std::ostream &os) \ | |
{ \ | |
os << #OPCHARS; \ | |
} \ | |
}; \ | |
\ | |
template <typename L, typename R> \ | |
expression_enable<L, \ | |
expression_enable<R, \ | |
binary_expression<L, R, OPNAME> \ | |
> \ | |
> \ | |
operator OPCHARS(L l, R r) \ | |
{ \ | |
return { l, r, OPNAME{} }; \ | |
} | |
BINARY_OPERATOR(-, sub); | |
BINARY_OPERATOR(+, add); | |
BINARY_OPERATOR(<<, lshift); | |
BINARY_OPERATOR(>>, rshift); | |
// TODO others | |
// TODO unary |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "operators.hpp" | |
#include <iostream> | |
int main() | |
{ | |
identifier_expression a = {"a"}, b = {"b"}, c = {"c"}, d = {"d"}, e = {"e"}; | |
(a + b + c + d + e).print(std::cout << std::endl); | |
(a << b + c << d + e).print(std::cout << std::endl); | |
(a << b >> c - d + e).print(std::cout << std::endl); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment