Browse DevX
Sign up for e-mail newsletters from DevX


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




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

Binding a Function Object
The same std::tr1::function object may change its target, even if the original target and the new target have radically different implementations. In the following example, the object func2 is first bound to the freestanding function adjacent(). Later, the same func2 is bound to a function object:

using namespace std; bool adjacent(int x, int y){return x == y-1 || x == y+1;} class Data { private: vector <pair<int, int> > records; public: bool operator()(int x, int y) { records.push_back(make_pair(x, y)); return x < y; } }; function <bool(int, int)> func2; func2 = &adjacent func2(2, 3); // calls adjacent(2, 3), returns true Data rec; func2 = ref(rec); //see note func2 (5, 2)); // adds pair<5, 2> to rec.records

Author's Note: The std::tr1::function specification makes use of another TR1 feature called reference wrapper classes. I will discuss reference wrappers in a future 10-Minute Solution, but for the time being, assume that ref() is a standard helper function that takes an argument of type X and returns an object whose interface simulates a X& object.

You may also assign two std::tr1::function objects whose return types and arguments are different if there is an implicit conversion between those types:

func2=func;//OK, long return value is convertible to bool

Implicit Boolean Conversion
std::tr1::function defines a Boolean conversion operator that enables you to use objects of this type in Boolean expressions:

std::tr1::function f<int (int,int>) f; assert (!f); //OK, f is empty f=&add assert (f); //OK, f isn't empty void func(function <int (int,int>) &f1); { if(f1) { f1(2,3); } else { f1=&subtract f1(3,2); } }

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