Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Intermediate
Feb 1, 2005



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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

	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;
	functor f(b);
Saurabh Ramya
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date