Advertisement
Guest User

Untitled

a guest
May 27th, 2012
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class stack {
  2. // Implementation left to the user
  3. // but it's not teh hards
  4. template<typename T> void push(T&& t);
  5. template<typename T> T& GetElement(int index); // negative for relative
  6. void Pop();
  7. };
  8. class Instruction {
  9. public:
  10. virtual void call(stack& s) = 0;
  11. };
  12. template<typename T> class push : public Instruction {
  13. public:
  14. push(T arg)
  15. : t(std::move(arg)) {}
  16. T t;
  17. void call(stack& s) {
  18. push<T>(t);
  19. }
  20. };
  21. template<typename T> class add : public Instruction {
  22. public:
  23. add(int i1, int i2)
  24. : index1(i1), index2(i2) {}
  25. int index1;
  26. int index2;
  27. void call(stack& s) {
  28. push(GetElement(index1) + GetElement(index2));
  29. }
  30. };
  31. // Use factory to make this easier in reality
  32. // and variadics
  33. // Also specialize for void return
  34. template<typename Ret, typename Arg> class call : public Instruction {
  35. public:
  36. call(std::function<Ret(Args)> the_f, int args) // Un-sure what went here
  37. : f(std::move(the_f))
  38. {
  39. index = args;
  40. } // but you get the gist
  41. std::function<Ret(Args)> f;
  42. int index;
  43. void call(stack& s) {
  44. push<Ret>(GetElement(index));
  45. }
  46. };
  47. int main() {
  48. stack s;
  49. std::vector<std::unique_ptr<Instruction>> func;
  50. func.push_back(make_unique(push<std::string>("hello")));
  51. func.push_back(make_unique(push<std::string>(" world")));
  52. func.push_back(make_unique(add<std::string>(-1, -2)));
  53. func.push_back(call<void(std::string)>([](std::string s) { std::cout << s; }, -1);
  54. std::for_each(func.begin(), func.end(), [&](std::unique_ptr<Instruction>& p) {
  55. p->call(s);
  56. });
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement