如果知道参数并返回类型,如何使用其指针调用任何类函数?

问题描述 投票:2回答:1

如何创建指向仅知道参数和返回类型的任何类函数的函数指针?以后如何调用此函数?

我了解了std :: function,但是我不知道如何在不使用特定类名(例如“ 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);
}

如何创建指向仅知道参数和返回类型的任何类函数的函数指针?以后如何调用此函数?我读到有关std :: function的信息,但是我不知道如何...

c++ c++17 function-pointers
1个回答
1
投票

首先,identifiers beginning with an underscore is reserved in the global namespace,所以您不应该声明类似_collection的名称。

© www.soinside.com 2019 - 2024. All rights reserved.