Skip to content

Instantly share code, notes, and snippets.

@Qix-
Created January 21, 2019 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Qix-/9d306b15ff1c7523cf5b7003923cb60c to your computer and use it in GitHub Desktop.
Save Qix-/9d306b15ff1c7523cf5b7003923cb60c to your computer and use it in GitHub Desktop.
Abusing pointer casts to store any function and call it with a parameter pack at runtime
#include <iostream>
#include <string>
#include <functional>
#include <tuple>
using namespace std;
template <typename... TArgs>
void cast_apply(function<void()> fn, tuple<TArgs...> tup) {
function<void(TArgs...)> realFn = *reinterpret_cast<function<void(TArgs...)>*>(&fn);
apply(realFn, tup);
}
int main() {
int foo = 10;
function<void(int, int, string)> fn = [&foo](int a, int b, string c) {
cout << "foo=" << foo << endl;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
cout << "c=" << c << endl;
};
fn(1, 2, "first");
cout << "---" << endl;
function<void()> opaque = *reinterpret_cast<function<void()>*>(&fn);
auto tup = make_tuple(42, 69, string("second"));
foo = 9001;
cast_apply(opaque, tup);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment