我有一个成员,该成员是指向参数化函数的指针,我可以扩展参数类型吗?
I have member that is a pointer to a parameterized function, can I extend a parameter type?
>构造函数获取并设置一个类型为:
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
这样称呼 ( context
是 nullptr
)
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)));
相关文章:
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 使用指向成员的指针将成员函数作为参数传递
- 如何将lambda作为模板类的成员函数参数
- 将成员函数指针作为参数传递给模板方法
- c++构造函数成员初始化:传递参数
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 模板化检查是否存在带有参数列表的类成员函数?
- 如何将类成员方法的参数列表自动填充写入可变参数?
- 为什么我需要在成员发起器列表中重复基类的模板参数?
- C++向量默认为成员参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 可变参数模板参数扩展 类型为 std::function 的类成员
- 当类成员参数具有相同的名称时,如何定义构造函数?
- 类成员参数中的Constexpr
- 允许通过指向方法的成员参数的指针来推断模板参数所指向的成员类型
- 为什么未调用的模板类成员 *参数* 被实例化
- 如何访问指向C++类模板中成员参数的指针
- 我们是否需要在嵌套类型的成员参数前面加上"::"?
- 设计模式- c++运行时成员参数的实例化