diwatu
diwatu

Reputation: 5699

What exactly is the returned data type for a particular std::bind?

First I have to say I have to know the returned data type from std::bind.

I have a struct which is defined as

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

Func is a function holder, I want it to hold different kinds of callback function.

Somewhere I initialize CallBackItems like this:

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

When I try to use the 'Func' in each CALLBACK I have to cast it first and then use it like a function. So far I tried:

 //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))();

none of them work, anybody knows how to cast the returned variables from std::bind?

Upvotes: 2

Views: 712

Answers (1)

Daniel Frey
Daniel Frey

Reputation: 56863

The type returned from std::bind is unspecified:

20.8.9.1.3 Function template bind [func.bind.bind]

1 ...

template<class F, class... BoundArgs>
unspecified bind(F&& f, BoundArgs&&... bound_args);

You can use std::function to store them, e.g.

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

In your case, this mean you could need to cast the type when you store the result from 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) ) },                  
};

and then get it back with:

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

Upvotes: 4

Related Questions