some practical uses of mem_fn & bind

Fanatic23 picture Fanatic23 · Apr 14, 2012 · Viewed 7.6k times · Source

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.

Answer

josephthomas picture josephthomas · Apr 14, 2012

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.