【发布时间】:2020-03-24 21:20:08
【问题描述】:
如何创建一个指向任何只知道参数和返回类型的类函数的函数指针?以后怎么调用这个函数?
我阅读了有关 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);
}
【问题讨论】:
-
使用绑定 + 函数:demo
-
完美。但没有直接适用于我的情况,做了一些更改: void saveFuncAddr() {_collection.p = std::bind(static_cast
(&One::Foo_1),这个,std::placeholders::_1,std::placeholders::_2); }; -
非静态成员函数实际上有一个隐藏参数,它是指向类的指针(
this指针)。您的计划是否包括一种方法来指定应将哪个对象用于这些函数的隐藏参数?
标签: c++ c++17 function-pointers