Skip to content

Instantly share code, notes, and snippets.

@matovitch
Created September 12, 2018 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matovitch/ce259e74feba3622e9c99ffa51b1e612 to your computer and use it in GitHub Desktop.
Save matovitch/ce259e74feba3622e9c99ffa51b1e612 to your computer and use it in GitHub Desktop.
// http://coliru.stacked-crooked.com/a/5f6f08cff6f9a5b7
#include <iostream>
auto lit(const int value)
{
return [value](auto visitor) { return visitor.lit(value); };
}
template <class LHS,
class RHS>
auto add(LHS&& lhs,
RHS&& rhs)
{
return [lhs,
rhs](auto visitor) { return visitor.add(lhs(visitor),
rhs(visitor)); };
}
template <class LHS,
class RHS>
auto mul(LHS&& lhs,
RHS&& rhs)
{
return [lhs,
rhs](auto visitor) { return visitor.mul(lhs(visitor),
rhs(visitor)); };
}
struct EvalVisitor
{
int lit(const int value) const
{
return value;
}
int add(const int lhs,
const int rhs) const
{
return lhs + rhs;
}
int mul(const int lhs,
const int rhs) const
{
return lhs * rhs;
}
};
int main()
{
const EvalVisitor evalVisitor;
const auto expression = add(lit(1),
mul(lit(3),
lit(2)));
std::cout << expression(evalVisitor) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment