如何将 C 函数指针迁移到 C++?

How to migrate C function pointers to C++?

下面是在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);
}

它用$gcc main.c编译。

以下是我将其迁移到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);
}

尝试编译它,出现错误:

$ 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.

如何将 C 函数指针迁移到 C++?

在 C 中,void f()f 声明为采用未指定数量的参数和 returns int 的函数。在 C++ 中,它声明 f 是一个不带参数的函数,并且 returns int。在 C 中,如果您想编写一个不带参数的函数,您可以使用 void 作为参数列表:void f(void) 声明一个不带参数的函数并且 returns 什么都不带。

除非你有充分的理由不这样做,否则问题中的代码编写方式是void foo(void (*func)(int), int i)。也就是说 func 是一个指向函数的指针,该函数接受一个 int 和 returns void.

类型的参数