user2065501 user2065501 - 7 months ago 31
C++ Question

Accept both lambda-functions and function-pointers as argument

I have a function, let's say

void processSomething(Arg1 arg1, Function t){

I want both of the following usages to work:

processSomething(myArg1, [&](SomeVariable someVar){...});
void(*myFunc)(void) = &someFunc;
processSomething(myArg1, myFunc);

However, I found that I can't use the lambda-way when using
as parameter declaration.
Any way to have both usages work without two separate functions or an overly complicated use of wrappers?


Well, you have two choices:

  1. Templates:

    template<class F>
    void processSomething(Arg1 arg1, F t){

    This is the preferred way as it creates more efficient code, but at the cost of possible code-duplication.

  2. Using a std::function or such:

    void processSomething(Arg1 arg1, std::function<void(SomeVariable)> t){

    There's a runtime-cost to the indirections involved, but it will use the same code in each case.