std :: function - >函数指针 [英] std::function -> function pointer

查看:202
本文介绍了std :: function - >函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是一个代码:

#include <functional>
using namespace std::tr1;

typedef void(*fp)(void);

void foo(void)
{

}

void f(fp)
{

}

int main()
{
  function<void(void)> fun = foo;
  f(fun); // error
  f(foo); // ok
}

最初我需要从非静态类方法,因为我需要在函数调用之间保存数据。我尝试了 std :: tr1 :: bind boost :: bind ,但他们返回函数对象,其中,我可以看到,不能铸到纯函数指针。虽然函数签名( SetupIterateCabinet )需要一个纯func指针。

Originally i need to make a function pointer from non-static class method because i need to save data between function callings. I tried std::tr1::bind and boost::bind, but they return functional object, not pointer, which, as i can see, can't be "casted" to pure functional pointer. While the function signature (SetupIterateCabinet) demands a pure func pointer exactly.

我需要一个建议如何解决问题。谢谢

I need an advise how to solve the problem. Thank you.

推荐答案

您已经大大简单化了您的实际问题,把你的问题到的 XY问题。让我们回到您的真实问题:如何调用 SetupIterateCabinet 作为回调。

You've greatly oversimplified your real problem and turned your question into an XY problem. Let's get back to your real question: how to call SetupIterateCabinet with a non-static member function as a callback.

某些类:

class MyClass
{
public:
    UINT MyCallback(UINT Notification, UINT_PTR Param1, UINT_PTR Param2)
    {
        /* impl */
    }
};

为了使用 MyClass :: MyCallback 作为 SetupIterateCabinet 的第三个参数,您需要为上下文 c传递 MyClass * / code>参数,并使用一个简单的shim函数取得 Context 参数,并做正确的事情:

In order to use MyClass::MyCallback as the third argument to SetupIterateCabinet, you need to pass a MyClass* for the Context argument and use a plain shim function to take that Context argument and do the right thing with it:

UINT MyClassCallback(PVOID Context, UINT Notification, UINT_PTR Param1, UINT_PTR Param2)
{
    return static_cast<MyClass*>(Context)->MyCallback(Notification, Param1, Param2);
}

int main()
{
    MyClass mc;
    SetupIterateCabinet(_T("some path"), 0, MyClassCallback, &mc);
}

这篇关于std :: function - &gt;函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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