首先,来看下摘自网友的bind代码:
#include<iostream>
using namespace std;
namespace
{
class placeholder_ {};
placeholder_ __1;
}
template <typename R, typename T, typename Arg>
class simple_bind_t
{
private:
typedef R (T::*F)(Arg);
F f_;
T* t_;
Arg& a_;
public:
simple_bind_t(F f, T* t, Arg &a)
: f_(f), t_(t), a_(a)
{}
R operator()()
{
cout<<"operator 自动重载"<<endl;
return (t_->*f_)(a_);
}
};
template <typename R, typename T, typename Arg>
simple_bind_t<R, T, Arg> simple_bind(R (T::*f)(Arg), T* t, Arg& a)
{
return simple_bind_t<R, T, Arg>(f, t, a);
}
class bind_test
{
public:
void print_string(const std::string str)
{
printf("%s", str.c_str());
}
};
int main()
{
bind_test t;
std::string h = "hehe\n";
simple_bind(&bind_test::print_string, &t, h)();
}
以上实现的自定义的bind函数代码。
<
本文介绍了自定义bind函数的实现,通过分析简单的模板类`simple_bind_t`,阐述了其构造函数、成员变量以及`operator()`的作用,展示了如何在`main`函数中使用bind模板来调用特定对象的方法并传递参数,最终执行并输出结果。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



