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

标签 c++ boost c++11 std

首先我必须说我必须知道 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 Function template bind [func.bind.bind]

1 ...

template<class F, class... BoundArgs>
unspecified 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)();

关于c++ - 特定 std::bind 返回的数据类型到底是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19409904/

相关文章:

c++ - operator[] const 引用二维指针的重载

python - 编译 boost 时的地址模型错误

c++ - 在智能指针的双图中查找原始指针

c++ - boost::spirit:语义 Action block 中的多个语句

c++ - std::vector 初始化元素的 move/复制构造函数

c++ - 为什么我不能用 reset() 删除 unique_ptr<char[]>?

c++ - 为什么 glDrawArrays 不能在 mac 上使用 OpenGL 绘制

c++ - dynamic_cast 抛出的 std::bad_cast 异常

c++ - 在哪里可以找到++ 运算符的实现?

c++ - Boost C++ 库中 Log 函数的问题