Reputation: 8653
I am passing a function pointer to another function, and I want it to be default initialized, and this is what I am trying, but this gives syntax error
void bar(int i) {}
void foo(void (*default_bar=bar)(int)) {
//
}
The error :
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/f_13.d" -MT"src/BinarySearchTree_13.d" -o "src/BinarySearchTree_13.o" "../src/f_13.cpp"
In file included from ../src/f_13.cpp:10:
../src/tree.h:51: error: expected `)' before '=' token
../src/tree.h:51: error: 'foo' declared as function returning a function
../src/tree.h:51: error: expected ';' before ')' token
../src/tree.h:60: error: expected `;' before 'void'
make: *** [src/f_13.o] Error 1
Just a point that this works fine :
void foo(void (*default_bar)(int)) {
Upvotes: 2
Views: 2844
Reputation: 361322
If you use typedef
to simplify the problem:
typedef void (*fun_type)(int);
then you can figure out yourself:
void foo(fun_type default_bar = bar)
{
}
Easy, isn't it?
To make complex declaration easy, I use identity
which is defined as:
template<typename T> using identity = T;
Using it, you can write your function as:
void foo(identity<void(int)> default_bar = bar)
{
}
More examples where identity
simplify declarations:
identity<int[100][200]> * v;
which is same as:
int (*v)[100][200];
Another:
identity<int(int,int)> *function(identity<int(int,char*)> param);
which is same as:
int (*function(int (*param)(int,char*)))(int,int);
With identity
, the declaration definitely becomes a bit longer, but it also makes it easy to parse the tokens and understand them one-by-one; that way the whole declaration becomes easy!
Hope that helps.
Upvotes: 6