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.


Use the std::tr1::function Class to Generalize Callbacks-2 : Page 2




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

The recently standardized Library Extension Technical Report 1 (TR1) includes a new class template called std::tr1::function that generalizes the notion of a callable entity while mimicking pointers to functions in both syntax and semantics. std::tr1::function can wrap any function object, pointer to function or pointer to a member function that can be called with the same arguments and return types.

A declaration of an std::tr1::function object includes the return type and the arguments of the target function:

#include <functional> using std::tr1::function; function <long (int, int)> func;

You can assign to func any callable entity that returns long and takes two arguments of type int:

long add(int x, int y) { return x+y; } func = &add //assign a target function cout << func(1, 2) << endl; // calls add(1,2)

Unlike with ordinary pointers to functions, the return type and the arguments of the target function may differ from those of func so long as there is an implicit conversion between those types. The following code listing demonstrates this property. It binds a function whose arguments are of type long, long to a std::tr1::function object whose arguments are of type int, int:

long subtract(long x, long y) { return x-y; } func = &subtract //OK, implicit conversion of arguments cout << func(2, 1) << endl; // output: 1

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