代码之家  ›  专栏  ›  技术社区  ›  AngusTheMan

C++结构中的回调

  •  2
  • AngusTheMan  · 技术社区  · 6 年前

    struct还有许多其他变量,但下面给出了一个示例:

    class MYCLASS
    {
    public:
        MYCLASS();
    
        struct TEST{
            std::function<int(int)> foo;
        };
    
        int plus(int x){
            return x + 1;
        }
    
        int minus(int x){
            return x - 1;
        }
    
        void sim(){
            TEST T;             // make an instance of TEST
            T.foo = plus(5);    // assign TEST.foo a function (plus or minus)  
            T.foo();            // call the method we assigned
        }
    };
    

    sim 方法,我要创建 test plus minus ,取决于某些标准。两行我都试着给出例子 T 函数并随后调用它是不正确的。

    2 回复  |  直到 6 年前
        1
  •  1
  •   HugoTeixeira    6 年前

    如果你想把电话推迟到 T.foo

        T.foo = [this](int x) { return plus(x); };
        T.foo(5);
    
        2
  •  1
  •   JeJo    6 年前

    选项-1

    plus() minus() 如果像您所展示的那样足够简单,您可以将它们作为结构中的lambda函数 TEST 自从 捕获更少的羔羊 可以存储 在类型化函数指针中 ,以下将执行您想要的操作。 See live demo

    #include <iostream>
    class MYCLASS
    {
        int m_var = 5; // just for demonstration
    public:
        MYCLASS() = default;
        struct TEST
        {
            using fPtrType = int(*)(int);   // function pointer type
            const fPtrType foo1 = [](int x) { return x + 1; };  // plus function
            const fPtrType foo2 = [](int x) { return x - 1; };  // minus function
        };
    
        void sim()
        {
            TEST T;
            std::cout << "Answer from int PLUS(int): " << T.foo1(m_var) << std::endl;
            std::cout << "Answer from int MINUS(int): " << T.foo2(m_var) << std::endl;
        }
    };
    

    如果上述内容在代码中发生了很大的变化,请再次对成员函数使用类型化函数指针,并执行以下操作:;这将避免 不必要的复制 (通过捕获)lambda的类实例 模板实例化 以及其他 performance issues 来了 with std::function 也。

    See live demo

    #include <iostream>    
    class MYCLASS
    {
        using fPtrType = int(MYCLASS::*)(int); // class member function pointer type
    public:
        MYCLASS() = default;
        struct TEST { fPtrType foo = nullptr; };
    
        int plus(int x) { return x + 1; }
        int minus(int x) { return x - 1; }
    
        void sim()
        {
            TEST T;
            T.foo = &MYCLASS::plus; // now you can
            std::cout << "Answer from int PLUS(int): " << (this->*T.MYCLASS::TEST::foo)(5) << std::endl;
                                                         //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ syntax would be a bit ugly
            // later same ptr variable for minus()
            T.foo = &MYCLASS::minus;
            int answer = (this->*T.MYCLASS::TEST::foo)(5);
            std::cout << "Answer from int MINUS(int): " << answer << std::endl;
        }
    };
    
    int main()
    {
        MYCLASS obj;
        obj.sim();
        return 0;
    }
    

    输出:

    Answer from int PLUS(int): 6
    Answer from int MINUS(int): 4