简体   繁体   English

获取指向非 static 成员 function 的 function 指针

[英]Obtaining a function pointer to a non static member function

Suppose I have a class:假设我有一个 class:

class A {
public:
    A(); 
    void myFunc();
};

Then at a different point in the program I create an instance of class A, and attempt to obtain a function pointer to myFunc() :然后在程序的不同点创建 class A 的实例,并尝试获取指向myFunc()的 function 指针:

A* a = new A;

//ATTEMPTS AT RETRIVING FUNCTION POINTER FOR A::MYFUNC

std::function<void()> fnptr = a->myFunc;

std::function<void()> fnptr(std::bind(A::myFunc, &a);

But both of these attempts present the error "call to non static member function without object argument"但是这两种尝试都出现错误“在没有 object 参数的情况下调用非 static 成员 function”

Perhaps both of these attempts are totally off the mark, but essentially im trying to obtain a function pointer to the myFunc() function in the specific instance of a .也许这两种尝试都完全不合时宜,但本质上我是在尝试获取a myFunc()指针,指向 . Any help on how to do so is appreciated:)任何有关如何这样做的帮助表示赞赏:)

I'm trying to obtain a function pointer to the myFunc() function我正在尝试获取指向myFunc() function 的 function 指针

Obtaining a pointer to member function for A::myFunc() can be done:可以为A::myFunc()获取指向成员 function 的指针:

void (A::*memFuncPtr)() = &A::myFunc;

or even better, taking advantage of auto :甚至更好,利用auto

auto memFuncPtr = &A::myFunc;

However, to dereference this pointer (ie, to call the member function it points to), you will eventually need an A object. This object corresponds to the one the member function will be called on.但是,要取消引用此指针(即调用它指向的成员 function),您最终将需要一个A object。此 object 对应于将调用的成员 function。

You can dereference the pointer to member function, memFuncPtr , either in combination with an A object and the .* operator:您可以将指向成员 function 的指针memFuncPtrA object 和.*运算符结合使用:

A a;
a.*memFuncPtr();

or in combination with a pointer to an A object and the operator ->* :或者结合指向A object 的指针和运算符->*

A *aPtr = new A();
aPtr->*memFuncPtr();

As a result, you would need to keep a reference to the object or a copy of it in order to create std::function<void()> out of this pointer to member function.因此,您需要保留对 object 的引用或其副本,以便从指向成员 function 的指针创建std::function<void()>

std::invoke

Since C++17, you can simply use the std::invoke() function template instead of .* / ->* .自 C++17 以来,您可以简单地使用std::invoke() function 模板代替.* / ->* It unifies the syntax for the two cases exposed above:它统一了上面公开的两种情况的语法:

std::invoke(memFuncPtr, a);
std::invoke(memFuncPtr, aPtr);

You need the following syntax:您需要以下语法:

std::function<void()> fnptr(std::bind(&A::myFunc, a));

You could also use a lambda expression like this:您还可以像这样使用 lambda 表达式:

auto fn = [a] { a->myFunc(); };

Here's a demo .这是一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM