Reputation: 29
I'd like to write a sort-of wrapper function for my class... And i really dont know how to do that!
See, i want a, say, run()
, function, to accept a function as an argument, thats the easy part.
The usage would be something like
void f() { }
void run(int (*func)) {
//whatever code
func();
//whatever code
}
run(f);
That should just run the f()
function, right?
But what if f()
had required arguments? Say it was declared as f(int i, int j)
, i would go along rewriting the run()
function to separately accept those int
s, and pass them to the f()
function.
But I'd like to be able to pass Any function to run()
, no matter how many arguments, or what type they are. Meaning, in the end, i'd like to get usage similar to what i would expect the hypothetical
void f() {int i, int j}
void v() {char* a, int size, int position}
void run(int (*func)) {
//whatever code
func();
//whatever code
}
run(f(1, 2));
run(v(array, 1, 2));
to do. I know it looks dumb, but i think i'm getting my point across.
How would i do that?
Please remember that this is arduino-c++, so it might lack some stuff, but i do believe there are libraries that could make up for that...
Upvotes: 0
Views: 896
Reputation: 169518
If you have access to std::function
then you can just use that:
void run(std::function<void()> fn) {
// Use fn() to call the proxied function:
fn();
}
You can invoke this function with a lambda:
run([]() { f(1, 2); });
Lambdas can even capture values from their enclosing scope:
int a = 1;
int b = 2;
run([a, b]() { f(a, b); });
If you don't have std::function
but you can use lambdas, you could make run
a template function:
template <typename T>
void run(T const & fn) {
fn();
}
Upvotes: 2