Last active
September 19, 2016 13:01
-
-
Save acgetchell/3517149a29a9361cee4c7f12b4c3a9ea to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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