简体   繁体   中英

How do I default initialize function pointer in c/c++?

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)) {

这条路:

void foo(void (*default_bar)(int) = bar)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM