如何从 std::function 获取这个指针? [英] How to get this pointer from std::function?

查看:39
本文介绍了如何从 std::function 获取这个指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于std::function可以保存成员函数,所以它必须在某处存储一个指向对象实例的指针.

Since std::function can hold member functions, so it must store a pointer to the object instance somewhere.

如何从包含成员函数的 std::function 获取 this 指针?

How can I fetch the this pointer from a std::function that holds a member function?

推荐答案

std::function 类型的对象拥有一个 可调用对象.指向成员函数的指针是一种可调用对象;可以使用适当类类型的参数以及它需要的任何其他参数来调用它.例如:

An object of type std::function holds a callable object. A pointer to member function is a kind of callable object; it can be called with an argument of the appropriate class type, plus any additional arguments that it needs. For example:

struct S {
    void f(int);
};
std::function<void(S, int)> g(&S::f);

要调用它,传递一个 S 类型的对象:

To call it, pass an object of type S:

S s;
g(s, 3);

注意std::function对象保存S对象;只有当你调用它时,函数指针才会被绑定到一个对象上.

Note that the std::function object does not hold an S object; it's only when you call it that the function pointer gets bound to an object.

这篇关于如何从 std::function 获取这个指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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