我有两个结构,struct B 继承自 struct A。我想将一个函数作为参数从 struct B 传递给 struct A 以供 struct A 使用。
这是我想要实现的目标和我遇到的问题的示例,完整代码将是 TL;DR。
struct A
{
int32 mynum;
void Tick(float delta, bool doThis, void (funcparam)(float, bool, int32))
{
funcparam(delta, doThis, mynum);
}
};
struct B : public A
{
void RunThis(float deltaTime, bool doIt, int32 which)
{
// do something when called by Struct A
};
void DoSomething()
{
Tick(0.1f, true, &B::RunThis);
};
};
问题出在这一行:Tick(0.1f, true, &B::RunThis);
来自函数 void DoSomething()
除非我已经完成了从一开始就错了,但我想我传递错了,因为它仍在我当前定义的结构的 header 中?
错误(我修改了错误以适合我的示例,我不认为我搞砸了..):
错误 C2664:“void A::Tick(float,bool,void (__cdecl *)(float,bool))”:无法从“void (__cdecl B::*)(float, bool)' 到 'void (__cdecl *)(float,bool)'
从 &B::RunThis
中省略 B::
当然不会解决任何问题。
最佳答案
第一个选项:改用虚函数。
如果每个派生类有 1 个且只有 1 个函数,效果最好。
struct A {
virtual void RunThis(float deltaTime, bool doIt, int32 which) = 0;
void Tick(float delta, bool doThis )
{
//...
RunThis(delta, doThis, which);
// ...
}
virtual ~A() // virtual destructor...
{}
};
struct B : public A
{
virtual void RunThis(float deltaTime, bool doIt, int32 which )
{
}
void DoSomething(/*...*/)
{
// ...
Tick(/*...*/);
}
};
第二个选项:std::function + lambda 或 struct B 中的成员函数
#include <functional>
struct A
{
void Tick(float delta, bool doit, std::function<void(float,bool,int32)> action )
{
}
};
struct B : public struct A
{
void DoSomething( /*...*/ )
{
// you can use a lambda, if convenient...
Tick(/*...*/,
[this](float delta, bool doit, int32_t which) -> void {
// ...
});
}
// or you can also use a pointer to member:
void RunThis(/*...*/) { /* ... */ }
void DoSomething(/*...*/)
{
std::function<void(float,bool,int32)> f = std::bind( &B::RunThis, this, _1,_2,_3);
Tick(/*...*/, f);
}
};
关于C++传递结构函数作为继承结构中函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36110411/