I have a function which takes arguments, default arguments and finally, a pointer to another function and a void pointer.
As an example, consider the following
int foo(double arg 1, bool arg 2, int arg3=0, int arg4=2, bool (*pbar)(bool,void*), void* data=0);
It is called in several places across my codebase. I have noticed that when the function pointer itself has arguments, then the default arguments, it is required that the default parameters must also be specified, even if the value I desire is the default one. For instance, the following code will compile
foo(arg1, arg2, pbar);
But the below snippet will not
foo(arg1, arg2, pbar, (void*) myint);
As a more complete example, here is a working snippet.
#include <iostream>
using namespace std;
int foo(double arg1, bool arg2, int arg3=0, int arg4=2, bool (*pbar)(bool,void*)=0, void* data=0)
{
return 1;
}
bool bar(bool bt, void* vs)
{
return false;
}
int main()
{
double arg1 = 0.0;
bool arg2 = false;
bool bt = true;
int i = 1;
void* vs = &i;
bool pbar = bar(bt, vs);
// no defaults specified and no function pointer arguments
foo(arg1, arg2, pbar);
// specify one of the defaults
int arg3 = 23;
foo(arg1, arg2, arg3, pbar);
// don't specify the defaults, but give arguments to function pointer
//foo(arg1, arg2, pbar, bt, vs);
return 0;
}
The final commented call will not compile.
So my question is, why upon the specification of the function pointer arguments does this fail to compile?
I have already found a solution to the problem by using the 'named parameter' method. Whereby I create a class and instantiate members with references. However, I am interested in an in-depth explanation as to why the above fails.
The error is presented below
main.cpp: In function ‘int main()’:
main.cpp:41:33: error: invalid conversion from ‘void*’ to ‘bool (*)(bool, void*)’ [-fpermissive]
foo(arg1, arg2, pbar, bt, vs);
^
main.cpp:13:5: note: initializing argument 5 of ‘int foo(double, bool, int, int, bool (*)(bool, void*), void*)’
int foo(double arg1, bool arg2, int arg3=0, int arg4=2, bool (*pbar)(bool,void*)=0, void* data=0)
^~~
I believe this is because the order of the parameters is messed up. However, why can I insert the function pointer and not worry about the default arg3 and arg4?
std::functionbut it has overhead. Function pointer is the least flexible IMHO. It is unrelated to your error though, and your problem is unrelated to function pointerbool pbar = bar(bt, vs);should bebool (*pbar)(bool, void*) = bar;