Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading