Can someone recommend some cool practical uses of tr1's mem_fn and bind utilities? I don't need esoteric c++ for library development. just some application level coding which makes uses of these.
any help will be very appreciated.
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;
}
I have used std::mem_fn
and std::bind
for reflection style properties.
So I would have a class SomeClass
with a vector of AbstractProperty
. There can be several different types of classes from AbstractProperty
, such as PropertyFloat
, PropertyU32
, etc.
Then in SomeClass
I will bind
to a std::function
for AbstractProperty
. I would bind
by doing
std::bind(std::mem_fn(&SomeClass::SomeFloatGetter), this)
For a setter type function, I would use
std::bind(std::mem_fn(&SomeClass::SomeSetterGetter), this, std::placeholders::_1)
Of course, to set the functions to the class is more difficult, but I do use a std::function
to do so. In PropertyFloat
I have
typedef std::function<float(void)> GetterType;
So it set it via a function, I would pass the first std::bind
I showed as the parameter for
typename PropertyFloat::GetterType getter
Of course, the types could make use of templates and be more generic, but that is a trade off depending on what you are developing for.
Normally it can be quite a hassle to use member functions for callbacks, for example for use in the <algorithm>
functions. std::mem_fn
(it's been standardized now, so you shouldn't need to use the tr1
namespace anymore) creates a callable object that can be used as the functor object of those functions. For an example of its use, see the examples section of this link which uses std::string::size
.
std::bind
can be used when e.g. you don't know the actual arguments at compile-time, but have to create a callable object with arguments runtime. It can also be used to reorder arguments, example:
auto f1 = std::bind(printf, _2, _1);
f1(42, "%d\n");
(Okay, stupid example, but all I could think of right now.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With