Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1750746
  • 博文数量: 100
  • 博客积分: 10122
  • 博客等级: 上将
  • 技术积分: 4092
  • 用 户 组: 普通用户
  • 注册时间: 2005-07-04 20:28
文章分类

全部博文(100)

文章存档

2010年(2)

2009年(28)

2008年(70)

我的朋友

分类: C/C++

2009-11-12 06:51:27

C 传统 callback 通常类似于

typedef int (*Callback)(void*, int);


第一个是callback数据,后面是callback参数列表

C++ 的 function object 则是 class 和 成员函数(通常用operator(...))

以下例子提供了一种方案让函数同时支持这两种回调:


#include <iostream>
#include <boost/lambda/lambda.hpp>
#include <boost/utility/addressof.hpp>

#define DYNC_FLAGS -std=c++0x

typedef int (*Callback)(void*, int);

static void A(Callback callback, void *data) {
    std::cout << callback(data, 0) << std::endl;
}

template <typename T>
int CallbackFunctor(void *functor, int i) {
    return (*(T*)(functor))(i);
}

template <typename C>
void A(const C &c) {
    A(&CallbackFunctor<C>, (void*)boost::addressof(c));
}

static int inc(int i) {
    return i + 1;
}

int main() {
    A(inc);
    A(boost::lambda::_1 + 2);

    /* this only works under C++0x, comment out if you don't have them */
    auto t = boost::lambda::_1 + 2;
    A(t);
}


auto 是 C++ 0x 的关键词,如果你用的是 gcc,可以用 -std::c++0x 通过编译。值得注意的是 boost::addressof, 因为 C++ 的 unary operator & 是可以重载的,为了获得对象的地址,最保险的是用 boost::addressof, 而不是直接使用 &a 表达式。

阅读(3053) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~