C++传递结构函数作为继承结构中函数的参数

标签 c++ struct parameter-passing

我有两个结构,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/

相关文章:

c++ - 在基于范围的循环中使用 lambda 的初始化列表

c++ - MS OPM(输出保护管理器)初始化 X509 链

c++ - boost intrusive 直接从节点获取下一个

c++ - 注入(inject) dll 在 Windows XP 上不起作用

c++ - 指向结构的指针的成员访问语法

c - 我什么时候应该使用地址为 '&' & 符号键的 scanf ?

objective-c - 使用单个对象/键替代 NSDictionary

c++ - 如何让 std::thread 对传递给它的函数的参数进行一般构造?

java - 将 Java 引用传递到对象链的最佳方式

r - 如何将列名作为参数传递给 dplyr 中的函数?