gpt4 book ai didi

c++ - 指向函数成员的指针

转载 作者:搜寻专家 更新时间:2023-10-31 00:10:43 28 4
gpt4 key购买 nike

我有一个 FreeRTOS 函数 xTaskCreate。简化的声明看起来像

typedef void (*TaskFunction_t)( void* );
unsigned xTaskCreate( TaskFunction_t pxTaskCode, void*params );

有两个类:

class Super {
virtual void task(void*params) = 0;
};
class Derived1 : public Super {
virtual void task(void*params){ while(1){ blinkLed(1); delay_ms(333); } }
};
class Derived2 : public Super { ... ;}

在函数 init() 中,我选择了一个派生类并创建了它的实例。然后想创建任务

void init(){
Super *obj = condition ? new Derived1 : new Derived2;
xTaskCreate( obj->task ); // WRONG.
}

更新。在 xTaskCreate 的简化声明中添加遗漏的 void*params

最佳答案

TaskFunction_t 只是指向函数的指针 - 因此它不能采用指向成员函数的指针。只是一个指向正常功能的指针。或者静态成员函数。或者没有捕获的 lambda。这是我们要利用的最后一个。

您从简化声明中删除的参数之一是 context :

 BaseType_t xTaskCreate(    TaskFunction_t pvTaskCode,
const char * const pcName,
unsigned short usStackDepth,
void *pvParameters, // <== this one!
UBaseType_t uxPriority,
TaskHandle_t *pxCreatedTask
);

您在参数中提供 Super* 并提供一个知道如何处理它的 lambda。总而言之:

void init(){
Super *obj = condition ? new Derived1 : new Derived2;
xTaskCreate([](void* o){ static_cast<Super*>(o)->task(); },
..., // other args here
obj,
... // more args
);
}

请注意,task() 不应带任何参数。 void* 是我们要转换为 Super* 的上下文。

关于c++ - 指向函数成员的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36987788/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com