如果我们知道参数和 return 类型,如何使用其指针调用任何 class 函数?

How to call any class function using its pointer if we know arguments and return type?

如何创建指向任何只知道参数和 return 类型的 class 函数的函数指针?后面怎么调用这个函数?

我读到了 std::function,但是我不知道如何在不使用特定 class 名称(如“std::function<void(const ClassName&, int)> f_add_display = &ClassName::func;

的情况下实现它

下面的例子不是为了编译,只是为了展示我的意思:

class collection {
    p* ...; //pointer to any(!) class function with known arguments and return type
} _collection;

class One {
public:
    ...
    bool Foo_1(int, int) {};
    void saveFuncAddr() {_collection.p = this::Foo_1};
};

class Two {
public: 
    bool Foo_2(int, int) {};
    void saveFuncAddr() {_collection.p = this::Foo_2};
};

int main() {
    one* = new One();
    one->saveFuncAddr();
    bool res1 = (*_collection.p)(1, 2);

    two* = new Two();
    two->saveFuncAddr();
    bool res2 = (*_collection.p)(1, 2);
}

首先,identifiers beginning with an underscore is reserved in the global namespace,所以你不应该声明像 _collection.

这样的名字

您可以使用 lambda 来包装您的成员函数:

#include <functional>

struct Collection {
    std::function<bool(int, int)> p; 
} collection;

class One {
public:
    bool Foo_1(int, int) {return true;}
    void saveFuncAddr() 
    {
        collection.p = [this](int a, int b){return this->Foo_1(a, b);};
    }
};

class Two {
public: 
    bool Foo_2(int, int) {return true;}
    void saveFuncAddr() 
    {
        collection.p = [this](int a, int b){return this->Foo_2(a, b);};
    }
};

int main() {
    auto one = new One();
    one->saveFuncAddr();
    bool res1 = (collection.p)(1, 2);
    delete one;

    auto two = new Two();
    two->saveFuncAddr();
    bool res2 = (collection.p)(1, 2);
    delete two;
}