Skip to content

Instantly share code, notes, and snippets.

@Databean
Created May 1, 2014 02:01
Show Gist options
  • Save Databean/00b8c282dc1cbe0d4b88 to your computer and use it in GitHub Desktop.
Save Databean/00b8c282dc1cbe0d4b88 to your computer and use it in GitHub Desktop.
Go interface attempt
#include <iostream>
#include <functional>
#include <memory>
#include <utility>
#include <vector>
#include <list>
template<typename R, typename... Args>
class GoInterface {
private:
class Interface {
public:
virtual R call(Args...) = 0;
};
template<class T, class Fn>
class Implementation : public Interface {
private:
T& wrapped;
Fn fn;
public:
Implementation(T& t, Fn fn) : wrapped(t), fn(fn) {}
virtual R call(Args... args) {
return (wrapped.*fn)(args...);
}
};
std::unique_ptr<Interface> impl;
public:
template<class T, class Fn>
GoInterface(T& wrapped, Fn fn) : impl(new Implementation<T, Fn>(wrapped, fn)) {}
R call(Args... args) {
return impl->call(args...);
}
};
////////////////////////////////////////////////////////////////////////
class StackInterface {
private:
GoInterface<void, const int&> pushFn;
GoInterface<void> popFn;
GoInterface<int&> peekFn;
public:
template<class T>
StackInterface(T& wrapped, void(T::* push)(const int&), void(T::* pop)(), int&(T::* peek)()) : pushFn(wrapped, push), popFn(wrapped, pop), peekFn(wrapped, peek) {}
void push(const int& t) { pushFn.call(t); }
void pop() { popFn.call(); }
int& peek() { return peekFn.call(); }
};
void useStack(StackInterface& myStack) {
myStack.push(5);
myStack.push(6);
std::cout << myStack.peek() << std::endl;
myStack.pop();
std::cout << myStack.peek() << std::endl;
}
int main() {
using std::vector;
using std::list;
vector<int> myVec;
StackInterface stackVector(myVec, &vector<int>::push_back, &vector<int>::pop_back, &vector<int>::back);
useStack(stackVector);
/*
list<int> myList;
StackInterface stackList(myList, &list<int>::push_back, &list<int>::pop_back, &list<int>::back);
useStack(stackList);*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment