特定 std::bind 返回的数据类型到底是什么?

2024-01-30

首先我不得不说我必须知道 std::bind 返回的数据类型。

我有一个结构体定义为

typedef struct
{
  UINT ID;
  CString NAME;
  boost::any Func;// 'auto' doesn't work here
} CALLBACK;
CALLBACK CallBackItems[];

Func是一个函数持有者,我希望它持有不同类型的回调函数。

我在某个地方初始化 CallBackItems,如下所示:

CallBackItems[] =
{       
    { 1,    L"OnReady",       std::bind(&CPopunderDlg::OnReady, pDlg)           },
    { 2,    L"CustomFunction",std::bind(&CPopunderDlg::OnFSCommond, pDlg,_1,_2) }   
   //...................    more items here         
};

当我尝试在每个回调中使用“Func”时,我必须先对其进行强制转换,然后像函数一样使用它。到目前为止我尝试过:

 //CallBackItems[0].Func is binded from pDlg->OnReady(), pDlg->OnReady() works here,
   boost::any_cast<function<void()>>(CallBackItems[0].Func)();

   ((std::function<void()>)(CallBackItems[0].Func))();

它们都不起作用,有人知道如何从 std::bind 转换返回的变量吗?


返回的类型来自std::bind未指定:

20.8.9.1.3 函数模板绑定 [func.bind.bind]

1 ...

template<class F, class... BoundArgs>
未指定 bind(F&& f, BoundArgs&&... bound_args);

您可以使用std::function存储它们,例如

void f( int ) {}
std::function< void(int) > f2 = std::bind(&f, _1);

就您而言,这意味着您在存储结果时可能需要转换类型std::bind:

CallBackItems[] =
{     
    { 1, L"OnReady", std::function< void() >( std::bind(&CPopunderDlg::OnReady, pDlg) ) },
    { 2, L"CustomFunction", std::function< void(int,int) >( std::bind(&CPopunderDlg::OnFSCommond, pDlg,_1,_2) ) },                  
};

然后用以下命令取回:

boost::any_cast<std::function<void()>>(CallBackItems[0].Func)();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

特定 std::bind 返回的数据类型到底是什么? 的相关文章

随机推荐