Cpper
C/C++高级工程师 Android高级软件工程师 IT集成工程师 音频工程师 熟悉c,c++,java,c#,py,js,asp等多种语言 程序猿
今天由于要写一些东西,遇到了需要把成员函数作为函数参数的问题
总结有以下几个办法:
1.使用类的静态成员:
      最简单的.只是这种办法与使用普通函数没有什么区别
2.模板的方法
 
1   template<class  T>   
2   void  Call(T* ptr,void(T::*MenFn)())   
3   {   
4      (ptr->*MenFn)();   
5   }   
   
 1 class MyClass
 2 {
 3 public:
 4     void Call()
 5     {
 6        
 7     }
 8 };
 9 
10 MyClass cs;
11 Call(&cs,&MyCall::Call);

3.  虚拟继承的方法
 1 class Base
 2 {
 3 public:
 4     virtual void Call() = 0;
 5 };    
 6 
 7 class SubClass :public Base
 8 {
 9 public:
10     void Call(){}
11 };
12  
13 void Call(Base *ptr)
14 {
15     ptr->Call();
16 

4.use boost.

 

 1#include   <boost/bind.hpp>   
 2#include   <iostream>   
 3using   namespace   std;   
 4struct   MyClass   
 5{   
 6    void  Print(const char* str)   
 7    {   
 8        cout<<"holle "<<str<<endl;   
 9    }
   
10}
;
11
12template<class _Fun>   
13void CallBackFun(_Fun a,const char* str)   
14{   
15    t(n);   
16}
   
17 
18int   main()   
19{   
20    MyClass mc;
21    CallBackFun(boost::bind(boost::mem_fn(&MyClass::Print),&mc,_1),"world")
22    return  1;   
23}
   
24

  5.使用静态成员函数或者联合体模拟之

1 union
2 {
3     void(G_CALL ParticleSystem::*PhysicsThreadFun)(void *arg);
4     ThreadFun f;
5 }fn; 
6 fn.PhysicsThreadFun = &ParticleSystem::PhysicsThreadFun;
7 thread_id = CreateThread(fn.f,&ps);

6.也许.
      对loki库不太熟悉也许上面也有答案吧
posted on 2010-02-23 19:08 ccsdu2009 阅读(6335) 评论(6)  编辑 收藏 引用
Comments
  • # re: c++中使用成员函数作为函数参数的方法
    sanit
    Posted @ 2010-02-23 22:38
    第二种方法11行,Call(&cs,&MyCall::Call);
    应该是&MyClass::Call吧?  回复  更多评论   
  • # re: c++中使用成员函数作为函数参数的方法
    ccsdu2009
    Posted @ 2010-02-24 08:27
    @sanit
    没问题的  回复  更多评论   
  • # re: c++中使用成员函数作为函数参数的方法
    XYFOR1234
    Posted @ 2010-02-24 10:30
    函数指针不行吗?是不是因为THIS指针的关系有一个偏移量?这也好解决,不过是编译器相关的。  回复  更多评论   
  • # re: c++中使用成员函数作为函数参数的方法
    zuhd
    Posted @ 2010-02-24 13:23
    void Call(Base *ptr)
    {
    ptr->Call();
    }

    直接这样传函数指针不就可以了吗?为什么要求是虚拟继承啊,普通的函数指针不行吗?  回复  更多评论   
  • # re: c++中使用成员函数作为函数参数的方法
    永远在一起
    Posted @ 2010-12-15 22:14
    谢谢,学习了,不过最后一种不怎么明白  回复  更多评论   
  • # re: c++中使用成员函数作为函数参数的方法
    porphyah
    Posted @ 2014-10-25 00:14
    如果Lambda表达式能与函数指针相互转化,那就能像C#一样轻轻松松写个临时的匿名函数了  回复  更多评论   

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理