Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to migrate C function pointers to C++?

The following is using a function pointer in C:

#include <stdio.h>
void bar1(int i){printf("bar1 %d\n", i+1);}
void bar2(int i){printf("bar2 %d\n", i+2);}
void foo(void (*func)(), int i) {func(i);};
int main() {
    foo(bar2, 0);
}

It compiles with $gcc main.c.

The following is my attempt to migrate it to C++:

#include <cstdio>
void bar1(int i){printf("bar1 %d\n", i+1);}
void bar2(int i){printf("bar2 %d\n", i+2);}
void foo(void (*func)(), int i) {func(i);};
int main() {
    foo(bar2, 0);
}

Trying to compile it, I get errors:

$ g++ main.cpp
main.cpp:7:39: error: too many arguments to function call, expected 0, have 1
void foo(void (*func)(), int i) {func(i);};
                                 ~~~~ ^
main.cpp:10:2: error: no matching function for call to 'foo'
        foo(bar2, 0);
        ^~~
main.cpp:7:6: note: candidate function not viable: no known conversion from 'void (int)' to 'void (*)()' for 1st argument
void foo(void (*func)(), int i) {func(i);};
     ^
2 errors generated.

How can I migrate C function pointers to C++?

like image 920
KcFnMi Avatar asked May 21 '26 20:05

KcFnMi


1 Answers

In C, void f() declares f to be function that takes an unspecified number of arguments and returns int. In C++ it declares f to be a function that takes no arguments and returns int. In C, if you want to write a function that takes no arguments you use void as the argument list: void f(void) declares a function that takes no arguments and returns nothing.

Unless you have a good reason to do otherwise, the way to write the code in the question is void foo(void (*func)(int), int i). That says that func is a pointer to a function that takes one argument of type int and returns void.

like image 93
Pete Becker Avatar answered May 24 '26 13:05

Pete Becker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!