Skip to content

Instantly share code, notes, and snippets.

@Fiona-J-W
Created October 23, 2014 15:17
Show Gist options
  • Select an option

  • Save Fiona-J-W/3c86b1e152d43b897f46 to your computer and use it in GitHub Desktop.

Select an option

Save Fiona-J-W/3c86b1e152d43b897f46 to your computer and use it in GitHub Desktop.
Better Callback
#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