C++ void 作为参数,如 PHP

c++ void as parameter like PHP

本文关键字:PHP 参数 void C++      更新时间:2023-10-16

在PHP中,你可以创建一个函数作为另一个函数的参数。

例:

function example($stackoverflow) {
    $stackoverflow();
}
example(function() {
    echo "Hi StackOverflow !";
}

我想在C++这样做

void Window::clear()
{
    EnumChildWindows(g_hWnd, {}, NULL);
}

C++ 中的相应功能可通过函数对象std::function获得:

void call(function<void()> f) {
    f();
}

您传递的参数可以是命名函数,例如

void test() {
    cout << "test" << endl;
}
...
call(test);

lambda 函数,例如

call([]() { cout << "lambda" << endl; });

演示。

我想在C++使用WinAPI中的函数来做到这一点。

传递函数的另一种方法是使用函数指针,这是 WinAPI 使用的方法。您无法内联执行此操作,因为 API 不需要std::function,因此您必须声明一个命名函数以在调用中使用:

BOOL CALLBACK CheckWindow(HWND hwnd, LPARAM lParam) {
    ... // Your processing code goes here
    return TRUE;
}
...
EnumChildWindows(g_hWnd, CheckWindow, NULL);

指向函数的指针?

void func(void (*another_func)(void))
{
    another_func();
}
void func2(void)
{
    cout << "Hi StackOverflow!" << endl;
}
func(func2);

除了传递(命名的(函数或(未命名的(lambda(如Keine Lust和dasblinkenlight所示(之外,在面向对象的领域,你可能应该重新审视你的代码设计。通常,在 OOP 中,函数指针通常会过时,取而代之的是基于继承和函数重写的设计。请参阅以下简短程序,说明这可能意味着什么:

struct Printable {
    virtual void print() const = 0;
};
struct ObjType1 : Printable {
    void print() const override { cout << "Hello SO!" << endl; }
};
struct ObjType2 : Printable {
    void print() const override { cout << "Hello object orientation!" << endl; }
};
void callPrint(Printable &p) {
    p.print();
}
int main() {
    ObjType1 objT1;
    ObjType2 objT2;
    callPrint(objT1);
    callPrint(objT2);
}

一个纯粹的面向对象解决方案,可能有助于保持代码清晰和跨平台,受Java接口的启发:

//Define an C++ interface
class MyInterface 
{
public:
    virtual void func2(void) = 0;
}
//-------------------------------
//Define the function with parameter as interface
void func(MyInterface * pImplementation)
{
    pImplementation->func2();   //Call interface function
}
//-------------------------------
class MyImplementation : public MyInterface
{
public:
    printf("Do something ...n");
} myImpl;
func(&myImpl);  //Call function with interface implementation

在C++
中不可能这样做改为创建新函数。