0

I am trying to store a captureless lambda that has a default parameter to a function pointer. I have the below code working for a lambda with a default argument

#include <iostream>

int main()
{
decltype([](int a = 10) {  std::cout << a << std::endl;}) my_lambda {};

my_lambda();
my_lambda(21);
return 0;
}

I have also managed to convert to a function pointer

#include <iostream>
using command_t = bool (*)(int);
int main()
{
decltype([](int a = 10) {  std::cout << a << std::endl; return true;}) my_lambda {};
command_t testFunction(my_lambda);
//testFunction();
testFunction(21);
return 0;
}

But I lose the default parameter as I cannot uncomment the testFunction() and run it as the compiler tells me that it is expecting a parameter. How can I combine these two concepts and convert these lambdas to a function pointer and keep the default parameter? I am using gcc 10.2. Thanks.

  • 4
    The problem is that a default value isn't part of a function signature, so... I don't think it's possible have a function pointer with a default argument. – max66 Nov 23 '20 at 18:47
  • 1
    max66 is correct. It is also explained here https://stackoverflow.com/questions/9760672/howto-c-function-pointer-with-default-values – drel Nov 23 '20 at 18:51
  • @drel: Given the OP is aware of everything but "How to keep default parameter in a function pointer?" and the answer to that ("You can't") is in that question, I'm closing as a duplicate. – ShadowRanger Nov 23 '20 at 18:56
  • It is a bit of a workaround. But I was able to create a struct that has a function pointer member and then by overloading the call operator with a default parameter, I was able to keep the default parameter with the use of a function pointer. Now instead of having a vector or map of function pointers. I have a container of my struct and just use the call operator. – Matthew Pittenger Nov 23 '20 at 19:00
  • "But I was able to create a struct that has a function pointer member and then by overloading the call operator with a default parameter" - So you have reinvented the lambdas. – max66 Nov 23 '20 at 23:27

0 Answers0