我知道如何在std :: function (
std :: function<int(double)>
)中声明int fn(double)
。我知道如何编写指向成员函数的指针 (typedef int (A :: * MemFn)(double d);
)。但是,如何使用std :: function编写指向成员函数的指针?
如果您想编译/测试,请参考下面的虚拟代码
-根据答案,我认为我将只使用typedef,不再烦恼std :: function
#include <cstdio>
#include <functional>
struct A{ int fn(double){ return 0; } };
int fn2(double){ return 0; }
typedef int (A::*MemFn)(double d);
typedef std::function<int(double)> MemFn2;
void Test(A*a, MemFn2 fn){
fn(1.2f);
}
void Test(A*a, MemFn fn){
(a->*fn)(1.2f);
}
int main(){
Test(new A, &A::fn);
Test(new A, &fn2);
}
std::function<int(Type&)>
能够存储这种类型的自由函数:typedef int (*FunType)(Type&)
,即一个接受Type&
类型参数并返回int
的函数。 - Nawaztypedef int (A::*MemFn)(double d);
看起来更容易;)。我并不是很关心对象,只是如何指定函数指针。 - user34537std::function
使用的“可调用”定义。std::function
绝对可以存储和调用指向成员函数的指针。std::function
对象的第一个参数是适当类型的对象或指向这样的对象的指针。 - bames53