Created
October 23, 2014 15:17
-
-
Save Fiona-J-W/3c86b1e152d43b897f46 to your computer and use it in GitHub Desktop.
Better Callback
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 <algorithm> | |
| #include <string> | |
| #include <vector> | |
| #include <type_traits> | |
| #include <functional> | |
| #include <iostream> | |
| template<typename T> | |
| using fn = T*; | |
| void foo(int i, fn<void(int, void*)> callback, void* data) { | |
| std::cout << i << '\n'; | |
| callback(i, data); | |
| } | |
| template<typename Function, typename T> | |
| void good_foo(int i, Function callback, T&& data) { | |
| struct callback_data { | |
| Function callback; | |
| T&& data; | |
| }; | |
| auto bar = callback_data{callback, std::forward<T>(data)}; | |
| foo(i, [](int i, void* data) { | |
| auto tmp = reinterpret_cast<callback_data*>(data); | |
| tmp->callback(i, tmp->data); | |
| }, &bar); | |
| } | |
| int main() { | |
| int x = 5; | |
| good_foo(3, [&x](int i, std::string str) {std::cout << i << ", " << str << ", " << x << '\n';}, "blub"); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment