Some practical applications of mem_fn & bind

Can someone recommend some interesting practical applications of tr1 mem_fn and binding utilities? I don't need esoteric C ++ to develop a library. just some application level encoding that uses them.

Any help would be greatly appreciated.

+6
source share
3 answers

Typically, using member functions for callbacks can be quite difficult to use, for example, for use in <algorithm> functions. std::mem_fn (now standardized, so you no longer need to use the tr1 namespace), creates a callable object that can be used as a functor object for these functions. For an example of its use, see the examples section for this link , which uses std::string::size .

std::bind can be used when, for example, you do not know the actual arguments at compile time, but you must create a callable object with runtime arguments. It can also be used to change the order of arguments, for example:

 auto f1 = std::bind(printf, _2, _1); f1(42, "%d\n"); 

(Well, a stupid example, but all I could think of right now.)

+5
source

I used std::mem_fn and std::bind for reflection style properties.

So, I would have a class SomeClass with an AbstractProperty vector. There may be several different types of classes from AbstractProperty , such as PropertyFloat , PropertyU32 , etc.

Then in SomeClass I will bind up a std::function for AbstractProperty . I would bind execute

 std::bind(std::mem_fn(&SomeClass::SomeFloatGetter), this) 

For a function like setter, I would use

  std::bind(std::mem_fn(&SomeClass::SomeSetterGetter), this, std::placeholders::_1) 

Of course, setting functions to a class is more difficult, but I use std::function to do this. In PropertyFloat I have

 typedef std::function<float(void)> GetterType; 

So he installed it through a function, I would pass the first std::bind shown by me as a parameter to

 typename PropertyFloat::GetterType getter 

Of course, types can use templates and be more universal, but this is a compromise depending on what you are developing for.

+5
source

The following code counts the number of elements greater than five:

 #include <functional> #include <algorithm> #include <vector> #include <iostream> int main() { using namespace std; vector<int> v { 1, 5, 2, 7, 6, 7, 5 }; cout << count_if(v.begin(), v.end(), bind(greater<int>(), placeholders::_1, 5)) << endl; } 
+3
source

Source: https://habr.com/ru/post/913215/


All Articles