Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

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


advertisement
Instantiation
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.

 

 

Sitemap