C++接受成员和外部函数指针

标签 c++ function pointers

我有一个 Alpha 类和一个 pointFun 函数,它应该接受 Alpha 成员函数和通用外部函数(例如:定义在主要)。

我重写了 pointFun 以使其可用于 Alpha 成员函数和外部函数。但由于 pointFun 函数实际上很长,我想避免重复它两次。

有没有办法接受这两种函数指针类型?我尝试这样做(请参阅代码的注释部分)但它不起作用。

// fpointer.h

#include <iostream>
using std::cout;
using std::endl;

class Alpha {
    public:
        Alpha() {}

        void pointFun (void (Alpha::*fun)());
        void pointFun (void (*fun)());
        //void pointFun (void (*funA)(), void (Alpha::*funB)()); // <-- how to make THIS instead of the previous two?
        void printA   ();
        void assignF  ();

    private:
         int value;
        bool set;
};

void Alpha::pointFun(void (Alpha::*fun)()) {
    (Alpha().*fun)();
}

void Alpha::pointFun(void (*fun)()) {
    (*fun)();
}

/* // I want this:
void Alpha::pointFun(void (*funA)() = 0, void (Alpha::*funB)() = 0) {
    (*funA)();
    (Alpha().*funB)();
    // same code, different pointer functions
}
*/

void Alpha::printA() {
    cout << "A" << endl;
    // some long code
}

void Alpha::assignF () {
    pointFun(&Alpha::printA);
}

这是主要的:

// MAIN.cpp

#include <iostream>
#include "fpointer.h"
using namespace std;

void printB() {
    cout << "B" << endl;
    // same long code as before
}

int main() {
    Alpha A;
    A.pointFun(printB);
    A.assignF();
}

最佳答案

您可以创建一个方法,该方法采用 std::function 并针对您的特殊情况转发给它:

class Alpha {
public:
    void pointFun (std::function<void()> f); // Long function definition

    void pointFun (void (Alpha::*fun)()) { pointFun([this, fun](){(this->*fun)();}); }

// Other stuff
};

关于C++接受成员和外部函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31229731/

相关文章:

c++ - 在 C++ 中,字符串类型对象是否与 C 字符串对象一样是字符数组?

c++ - 如何从dll中的异步函数返回值

javascript - 为什么当调用 apply() 或 call() 时 'this' 指向函数内的 window ?

c++ - 为什么需要指针来初始化堆上的对象,而不是堆栈上的对象?

c - 使用指针传递结构时未声明的标识符

c++ - C++ 中的 STL : no match for 'operator*'

c++ - 为什么 std::is_same 不适用于 bool

javascript - jQuery - 尝试在 if 语句中执行函数

c - 如何将两个二维数组中的整数添加到用户指定长度的新二维数组中?

pointers - 在Golang中将结构指针转换为接口(interface)指针