我已经设法弄清楚如何使用std::bind
替换以前通过静态变量,静态函数和静态函数网络触发C风格回调(此处未显示)的一大堆代码编译器扩展__closure
。
此代码编译并成功运行;然而,在尝试稍微改进时,我得到了一个奇怪的编译器错误。
#include <iostream>
#include <string>
#include <functional>
typedef void MyFunc(std::string &);
struct Master
{
void func(std::string &s) { std::cout << "Master::func(" << s << ")\n"; }
void go();
Master() {}
private:
Master(Master const &);
};
int main()
{
Master m;
m.go();
}
void call_function( std::function<MyFunc> fp, std::string s )
{
fp(s);
}
template<typename FuncT, typename Host>
typename std::function<FuncT> my_binder(Host *h, FuncT Host::*p)
{
using std::placeholders::_1;
return std::bind(p, h, _1);
}
void Master::go()
{
std::string s("hello");
// OK
using std::placeholders::_1;
std::function<MyFunc> f = std::bind(&Master::func, this, _1);
call_function(f, s);
call_function( std::bind(&Master::func, this, _1), s );
// Undefined structure 'boost::function<void(std::string &)>'
my_binder(this, &Master::func);
// I'm hoping to end up here
// call_function( my_binder(this, &Master::func), s );
}
代码似乎适用于最新的g ++和clang,但是给出了
// Undefined structure 'boost::function<void(std::string &)>'
在另一个没有-c ++ 11支持的编译器上。我的代码是否正确(即失败的编译器有错误)?
另外:我是否可以使用预先存在的模板代替my_binder
?我的目标是让人们可以尽可能轻松地拨打call_function
,而不必包括std::placeholders
等等。当然,这可以通过预处理器宏实现,但使用模板函数会很好。