C++ void 作为参数,如 PHP
c++ void as parameter like PHP
在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++
中不可能这样做改为创建新函数。
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- C++ void 作为参数,如 PHP
- PHP 网站在传递图像作为参数时未运行 exec 函数
- 为什么我不能从C 发送多个参数到PHP
- 使用 php 将带有命令行可执行文件路径的参数传递
- 将多个参数从php传递到shell