Search code examples
c++functorstd-functiondefault-arguments

std::function to functions with default argument


#include <iostream>
#include <functional>

using MyFunctionAlias = std::function<void(int, double)>;

void exampleFunction(int value, double value2 = 3.14) {}

void exampleFunction2(int value, double value2) {}

int main() {
    MyFunctionAlias func = exampleFunction;

    // OK
    func(10, 2);

    // ERROR
    func(10);

    return 0;
}

The problem is that default arguments are not allowed in the declaration of the std::function object, so func must be invoked with all arguments.

In my application, I use MyFunctionAlias as member variable in different classes to have a generic type for various cases. In some classes, there are certain optional arguments. In those cases, I could simple provide dummy values for the optional arguments in the function call, but ideally I do not want to provide dummy values but call the function without the default arguments like above.

Is there a way to do this using function pointers?

There was a similar question here, but I think this solution only works when binding to always the same function -- I want to set func to different functions (func = exampleFunction2, func = exampleFunction3,...) depending on some run-time input.


Solution

  • If you don't need to use a std::function then you can just use a lambda like

    auto func = [](auto... vars){ return exampleFunction(vars...); }
    

    If you do not want to type all of that out you can use this LIFT() macro1 by Vittorio Romeo

    #define RETURNS(...) noexcept(noexcept(__VA_ARGS__)) \
         -> decltype(__VA_ARGS__){ return __VA_ARGS__; }
    
    #define LIFT(f) [](auto&&... xs) RETURNS(f(::std::forward<decltype(xs)>(xs)...))
    

    And you would use lit like

    auto func = LIFT(exampleFunction);
    

    1: see link for full details