首先我必须说我必须知道 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/