首先来看两个文章,function/bind的救赎(上),http://blog.csdn.net/myan/arti…,以boost::function和boost:bind取代虚函数,http://blog.csdn.net/solstice/…,前者讲背景和理论,后者讲实际操作和细节对比,读来酣畅淋漓,醍醐灌顶
这么好的东西,当然要想着怎么在现有的环境条件下用起来,没有 boost,但是幸运的是这东西已经进了 tr1,那么可以这么来
#include <stdio.h> #include <tr1/functional> using std::tr1::function; using std::tr1::bind; using std::tr1::placeholders::_1; class Foo { public: void methodA() { printf("method a\n"); } void methodInt(int a) { printf("method int %d\n", a); } }; class Bar { public: void methodB() { printf("method b\n"); } }; int main() { Foo foo; function<void()> f1 = bind(&Foo::methodA, &foo); f1(); Bar bar; f1 = bind(&Bar::methodB, &bar); f1(); f1 = bind(&Foo::methodInt, &foo, 42); f1(); function<void(int)> f2 = bind(&Foo::methodInt, &foo, _1); f2(53); return 0; }
得到输出
method a method b method int 42 method int 53
真是好用,不过需要注意的一点就是带了 tr1/functional 这东西之后,编译速度明显下来了很多
————————————————————–
2014-04-19 20:34:37 update
跟同学讨论之后,发现这个东西,其实可以这么来模拟
#include <stdio.h> typedef void (*fun)(void *, int, int); class Foo { private: void add(int a, int b) { printf("%d\n", a+b); } public: fun mybind() { fun f = (fun)&Foo::add; return f; } }; int main(int argc, char **argv) { Foo foo; fun f = foo.mybind(); f(&foo, 1, 2); return 0; }
看,虽然 add 是个私有函数,但是我们可以把他偷换出来,在外面去调用,不过需要注意,这个代码编译是有警告的
http://blog.csdn.net/jnu_simba/article/details/12944043
这个也不错
面向类设计的癌症 赞
VM_195_29_sles10_64:~/tmp> g++ –version
g++ (GCC) 4.1.2 20070115 (prerelease) (SUSE Linux)
VM_195_29_sles10_64:~/tmp> g++ bind.cpp
bind.cpp: In member function ‘void (* Foo::mybind())(void*, int, int)’:
bind.cpp:15: error: converting from ‘void (Foo::*)(int, int)’ to ‘void (*)(void*, int, int)’
最后的那段代码编译错误
确实,看来我之前是编译器老旧侥幸通过,不过 Foo::add 这个函数的参数列表确实是 (void*, int, int) 的,怎么把这个函数的指针弄出来是个问题