获取指向非静态成员函数的函数指针 [英] Obtaining a function pointer to a non static member function

查看:71
本文介绍了获取指向非静态成员函数的函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一堂课:

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

然后在程序的另一点,我创建一个类A的实例,并尝试获取指向 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():

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"

也许这两种尝试都不合时宜,但是本质上是试图在 a 的特定实例中获取指向 myFunc()函数的函数指针.对此方法的任何帮助,我们都感激不尽:)

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. Any help on how to do so is appreciated :)

推荐答案

您需要以下语法:

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

您还可以使用如下lambda表达式:

You could also use a lambda expression like this:

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

这是演示.

这篇关于获取指向非静态成员函数的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆