c++default-arguments

std::function and default function arguments


Here is simple example of using std::function

#include <iostream>
#include <functional>

//A function that sums two numbers.
//Arguments having default values.
void SumOfTwoNumbers(int a = 42, int b = 42)
{
    std::cout << "Sum of two numbers :: " << a + b << std::endl;
}

int main()
{
    std::function<void(int, int)> testFunc = SumOfTwoNumbers;

    SumOfTwoNumbers();          //Works
    testFunc();                 //Compile time error          
    testFunc(40, 40);           //Works

    return 0;
}

In the main function, there are three function calls. The first one and the last one works. Whereas the second call testFunc() without any arguments gives compile time error.

Shouldn't it consider the default arguments and execute successfully?


Solution

  • No, the default values for function arguments are not part of the function signature. They are evaluated at the call site only.

    You could use a lambda but then you'd need to redefine the default values:

    auto testFunc = [](int a = 42, int b = 42) { SumOfTwoNumbers(a, b); };
    

    ... and storing such a lambda in a std::function would again result in the same problem since the signature of the lambda is also void(int, int).


    You could however define your own wrapper functor (instead of using std::function) that has multiple operator() overloads:

    struct {
        void operator()() { SumOfTwoNumbers(42, 42); } 
        void operator()(int a) { SumOfTwoNumbers(a, 42); } 
        void operator()(int a, int b) { SumOfTwoNumbers(a, b); } 
    } testFunc;