Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class stack {
- // Implementation left to the user
- // but it's not teh hards
- template<typename T> void push(T&& t);
- template<typename T> T& GetElement(int index); // negative for relative
- void Pop();
- };
- class Instruction {
- public:
- virtual void call(stack& s) = 0;
- };
- template<typename T> class push : public Instruction {
- public:
- push(T arg)
- : t(std::move(arg)) {}
- T t;
- void call(stack& s) {
- push<T>(t);
- }
- };
- template<typename T> class add : public Instruction {
- public:
- add(int i1, int i2)
- : index1(i1), index2(i2) {}
- int index1;
- int index2;
- void call(stack& s) {
- push(GetElement(index1) + GetElement(index2));
- }
- };
- // Use factory to make this easier in reality
- // and variadics
- // Also specialize for void return
- template<typename Ret, typename Arg> class call : public Instruction {
- public:
- call(std::function<Ret(Args)> the_f, int args) // Un-sure what went here
- : f(std::move(the_f))
- {
- index = args;
- } // but you get the gist
- std::function<Ret(Args)> f;
- int index;
- void call(stack& s) {
- push<Ret>(GetElement(index));
- }
- };
- int main() {
- stack s;
- std::vector<std::unique_ptr<Instruction>> func;
- func.push_back(make_unique(push<std::string>("hello")));
- func.push_back(make_unique(push<std::string>(" world")));
- func.push_back(make_unique(add<std::string>(-1, -2)));
- func.push_back(call<void(std::string)>([](std::string s) { std::cout << s; }, -1);
- std::for_each(func.begin(), func.end(), [&](std::unique_ptr<Instruction>& p) {
- p->call(s);
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement