如何使用指向成员函数的指针进行切换

如何使用指向成员函数的指针进行切换

本文介绍了如何使用指向成员函数的指针进行切换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我只想做一个开关";使用函数指针,但使用方法指针.开关是,如果我调用方法 Run(),它将重定向到 A::RunOn()A::RunOff()code> 根据 Run ptr 指向这些成员函数.

Well, all I want to do is a "switch" with a function pointer, but with methods pointers. The switch is that if I call the method Run(), it will either redirect to A::RunOn() or A::RunOff() according to Run ptr is pointing to these member functions.

我知道这是可以做到的.我在普通的 c 中做到了,但我已经搜索并在 c++ 但没有运气.

I know it can be done. I did it in plain c but I have searched and googled to do the same thing in c++ but no luck.

class A
{
    typedef (void)(A::*RunPtr)(int);
    RunPtr RunMethod;

public:
    RunMethod Run;

    A()
    {
        Run = RunOff;
    }

    void SetOn(bool value)
    {
        if (value)
            Run = RunOn;
        else
            Run = RunOff;
    }

    void RunOn(int)
    {
        // RunOn stuff here
    }

    void RunOff(int)
    {
        // RunOff stuff here
    }
};

所以我可以调用 Run() 并且在函数调用之间会有一个切换,我认为这比仅仅这样做更有效:

So I can call Run() and there will be a switch between the function calls, which I think is more efficient than just doing:

if (on)
    RunOn();
else
    RunOff();

不知道怎么做!

推荐答案

您的成员函数指针 typedef 是错误的(尽管所示代码中存在其他问题).你需要

Your member function pointer typedef is wrong (Despite the other issues in the shown code). You need

typedef void(A::*RunPtr)(int);

或者你可以在A类的成员函数指针提供别名" rel="nofollow noreferrer">使用关键字如下:

Or you can provide the alias for the member function pointer of class A with the help of using keyword as follows:

using RunPtr = void(A::*)(int);
RunPtr RunMethod;

现在在SetOn中你可以做如下的成员指针赋值

Now in the SetOn you can do member pointer assignment as follows

void SetOn(bool value)
{
    RunMethod = value ? &A::RunOn : &A::RunOff;
}


现在,为了调用存储的成员函数指针,你可以/可以提供一个Run成员函数如下:

void  Run(int arg)
{
    std::invoke(RunMethod, this, arg);
    // do something...
}

调用成员函数有点棘手.但是,这可以使用更通用的std::invoke来自 标题(由于 c++17).

The call to member function is a bit tricky.However, this can be done using more generic std::invoke from <functional> header (Since c++17).

以下是完整示例:

#include <iostream>
#include <functional> //  std::invoke

class A
{
    using RunPtr = void(A::*)(int);
    // or with typedef
    // typedef void(A::*RunPtr)(int);
    RunPtr RunMethod;

public:
    void SetOn(bool value)
    {
        RunMethod = value ?  &A::RunOn : &A::RunOff;
    }

    void  Run(int arg)
    {
        std::invoke(RunMethod, this, arg);
        // do something...
    }

    void RunOn(int arg) { std::cout << "RunOn: " << arg << "\n"; }

    void RunOff(int arg) { std::cout << "RunOff: " << arg << "\n";  }
};

int main()
{
    A obj;
    obj.SetOn(true);
    obj.Run(1);       // prints: RunOn: 1
    obj.SetOn(false);
    obj.Run(0);       // prints: RunOff: 0
}

(观看演示)

这篇关于如何使用指向成员函数的指针进行切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 17:36