0

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 ints, 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...

0

1 Answer 1

2

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();
}
Sign up to request clarification or add additional context in comments.

5 Comments

Alright, i'll check if it works on my main project and report back!
Kay, i do not have std::function. The template solution seems to work, but i would also want the return type of the fn to be non void. A struct, infact. I know this isn't what i outlined in the post, but i thought that would be pretty straightforward... How would i make it so that i can do a returner=fn() in the run() function?
@TheFlazy Just pass in a lambda that returns something. In the run function you'll be able to assign the result. (I recommend auto result = fn(); so you don't have to care about the actual return type.)
how would i do that? Using your syntax i passed a function that does return stuff, tried assigning something to that return, and it didnt really work... @cdhowie
@TheFlazy What does "didn't really work" mean? Can you show your code and any error messages?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.