Skip to content

Instantly share code, notes, and snippets.

@acgetchell
Last active September 19, 2016 13:01
Show Gist options
  • Select an option

  • Save acgetchell/3517149a29a9361cee4c7f12b4c3a9ea to your computer and use it in GitHub Desktop.

Select an option

Save acgetchell/3517149a29a9361cee4c7f12b4c3a9ea to your computer and use it in GitHub Desktop.
#include <functional>
#include <iostream>
#include <vector>
int sum(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
struct multiply {
int operator()(int a, int b) { return a * b; }
};
struct divide {
int operator()(int a, int b) { return a / b; }
};
struct worker {
// Polymorphic function type
using element = std::function<int(int)>;
std::vector<element> queue_;
template <typename T> void queue(T&& callable) {
queue_.push_back(std::forward<T>(callable));
}
int go(int initial) {
int value = initial;
for (auto &item : queue_) {
value = item(value);
}
return value;
}
};
int main() {
worker my_worker;
// queue the work here
my_worker.queue([](int i) { return sum(i, 5); }); // sum 5
my_worker.queue([](int i) { return sub(i, 15); }); // sub 15
my_worker.queue([](int i) { return divide{}(i, 3); }); // div 3
my_worker.queue([](int i) { return sub(i, 10); }); // sub 10
my_worker.queue([](int i) { return multiply{}(i, 4); }); // mult 4
int result = my_worker.go(100);
std::cout << "result: " << result << std::endl;
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment