我有一个成员,该成员是指向参数化函数的指针,我可以扩展参数类型吗?

I have member that is a pointer to a parameterized function, can I extend a parameter type?

本文关键字:成员 参数 我可以 指针 扩展 类型 函数 有一个      更新时间:2023-10-16

>构造函数获取并设置一个类型为:

void (*callBackFunc)(void *context, VideoSprite *pCaller)

现在我需要扩展它以包含比VideoSprite保存更多的数据。我将像这样static_cast static回调:

static void staticFuncToInitRot(void *context, VideoSprite *pCaller)
{
    spinningSprite *winSpin = static_cast<spinningSprite*>(pCaller);

可以吗?没有切片或任何难以检测的风险?另外你能告诉我哪个c'tor会被叫出来,为什么?

    DelayedCallback(void *context, VideoSprite *pCaller, std::function<void(void *context, VideoSprite *pCaller)> lambda) :
        lambda(lambda),
        callBackFunc(NULL),
        context(context),
        pCaller(pCaller),
    {}
    DelayedCallback(void *context, VideoSprite *pCaller, void (*callBackFunc)(void *context, VideoSprite *pCaller)) :
        callBackFunc(callBackFunc),
        context(context),
        pCaller(pCaller),
    {}

只有一个替代成员NULL化,因为回调执行时间:

            if (callBackFunc) callBackFunc(context, pCaller);
            else lambda(context, pCaller);

我不记得我是否需要lambda或将其留在那里以获得感知的未来证明的好处。

c'tor 从 VideoSprite 这样称呼 ( contextnullptr

actionList.push_back(new DelayedCallback(context, this, callBackFunc));

其中callBackFunc是指向的指针

static void staticFuncToInitRot(void *context, VideoSprite *pCaller)

我真的不需要dynamic_cast感谢,感谢您的关注。

static void staticFuncToInitRot(void *context, VideoSprite *pCaller)
{
    spinningSprite *winSpin = static_cast<spinningSprite*>(pCaller);

可以吗?没有切片或任何难以检测的风险?另外你能告诉我哪个c'tor会被叫出来,为什么?

最好

执行一个dynamic_cast,以确保您不会意外地将另一个子类型的VideoSprite转换为spinningSprite并假设它是有效的转换。

static void staticFuncToInitRot(void *context, VideoSprite *pCaller)
{
    spinningSprite *winSpin = dynamic_cast<spinningSprite*>(pCaller);
    if ( winSpin )
    {
       // Safe to use the pointer
    }
}

至于将调用哪个构造函数...

当您使用:

actionList.push_back(new DelayedCallback(context, this, callBackFunc));

将调用第二个构造函数。我不知道你为什么觉得它模棱两可。第二个构造函数采用一个参数,其类型是正在使用的参数的直接匹配项。

可以使用以下命令强制使用第一个构造函数

actionList.push_back(new DelayedCallback(context, this, std::function<void(void *, VideoSprite *)>(callBackFunc)));