posts - 225, comments - 62, trackbacks - 0, articles - 0
   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

关于C++泛型函数指针

Posted on 2009-11-23 23:59 魔のkyo 阅读(2864) 评论(0)  编辑 收藏 引用 所属分类: Programming
如何实现Qt中signal/slot的绑定?
如何实现C#中的委托?

其核心在于定义一种泛型成员函数指针,但按照C++标准这似乎是不可能的,
C++的成员函数指针一直是一个比较难用的东西,可以说压根就没什么用。
关于上面两个问题我自己曾尝试了许多方法,未果,后,得知目前至少有两种东西可以帮助我实现
1. boost::function
2. FastDelegate     (http://www.codeproject.com/KB/cpp/FastDelegate.aspx)

这两个东西都使用了非标准化的东西,不过FastDelegate的作者已经完成了所有主流C++编译器的测试,并且FastDelegate的调用只会生成2行汇编代码,可以和普通的函数指针调用一样迅速。

#include <stdio.h>
#include 
"FastDelegate.h"

using namespace fastdelegate;

int add(int a,int b)
{
    
return a+b;
}

class Add
{
public:
    
int operator ()(int a,int b)
    {
        
return a+b;
    }

    
static int add(int a,int b)
    {
        
return a+b;
    }
};

int main(void)
{
    FastDelegate
< int(int,int> theDelegate1, theDelegate2, theDelegate3;

    Add tempAddObj;
    theDelegate1.bind(
&tempAddObj, &Add::operator() );  //绑定一个对象的成员函数
    printf("%d\n", theDelegate1(1,1));

    theDelegate2.bind(
&add);  //绑定一个普通函数
    printf("%d\n", theDelegate2(1,2));

    theDelegate3.bind(
&Add::add);  //绑定一个类的静态函数
    printf("%d\n", theDelegate3(1,3));
}


一年后,我发觉是可以用标准C++实现类似东西的
http://www.cnitblog.com/luckydmz/archive/2010/11/15/71336.html
只有注册用户登录后才能发表评论。