Created
January 21, 2019 22:25
-
-
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
This file contains 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 <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