C++ Programmer's Cookbook

{C++ 基础} {C++ 高级} {C#界面,C++核心算法} {设计模式} {C#基础}

Use Functor for Callbacks in C++

Use Functor for Callbacks in C++
Using the callback function in C is pretty straightforward, but in C++ it becomes little tricky.

If you want to use a member function as a callback function, then the member function needs to be associated with an object of the class before it can be called. In this case, you can use functor.

Suppose you need to use the member function get() of the class base as a callback function


class base

{
public:
	int get ()
	{ return 7;}
};
Then, you need to define a functor:

class CallbackFunctor
{
	functor(const base& b):m_base(b)
	{}
	int operator() ()
	{
		return m_base.get();
	}
};
Now you can use an object of CallbackFunctor as a callback function as follows.

Define the function that needs a callback to take an argument of type CallbackFunctor:


void call (CallbackFunctor& f)
{
	cout << f() << endl;
}


int main ()
{
	base b;
	CallbackFunctor f(b);
	call(f);
}

posted on 2006-01-18 08:56 梦在天涯 阅读(1587) 评论(5)  编辑 收藏 引用 所属分类: CPlusPlus

评论

# re: Use Functor for Callbacks in C++ 2006-01-19 10:16 fiestay

不错!但文中代码不能直接编译通过,稍微修改了一下,把我改过的代码贴上。
#include <iostream>

using namespace std;

class Base
{
public:
int get() { return 10; }
};

class Functor
{
public:
Functor(const Base& b):m_base(b)
{
}

int operator() ()
{
return m_base.get();
}

private:
Base m_base;
};

void call(Functor& f)
{
cout << f() << endl;
}

int main(int argc, char* argv[])
{
Base b;
Functor f(b);
call(f);

return 0;
}
  回复  更多评论   

# to 阵雨 2006-02-10 09:21 Holyfire

人家标题就是Use Functor for Callbacks in C++

WindProc是C风格的
再说了WindProc只是回调函数的应用,并不是回调函数的概念啊  回复  更多评论   

# re: Use Functor for Callbacks in C++ 2006-02-10 10:18 音乐虫子

wait not use boost::function ?  回复  更多评论   

# re: Use Functor for Callbacks in C++ 2006-02-14 21:40 阵雨

对不起,那我错了  回复  更多评论   

# re: Use Functor for Callbacks in C++ 2006-09-22 12:54 梦在天涯

fiestay改的很好,太谢谢了  回复  更多评论   


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


公告

EMail:itech001#126.com

导航

统计

  • 随笔 - 461
  • 文章 - 4
  • 评论 - 746
  • 引用 - 0

常用链接

随笔分类

随笔档案

收藏夹

Blogs

c#(csharp)

C++(cpp)

Enlish

Forums(bbs)

My self

Often go

Useful Webs

Xml/Uml/html

搜索

  •  

积分与排名

  • 积分 - 1795777
  • 排名 - 5

最新评论

阅读排行榜