user7140484 user7140484 - 1 year ago 101
C++ Question

How to replace std::ptr_fun with std::function and std::ref

I'm trying to learn the new features of C++11 and I have this code:

void print(int t, string separator)
cout << t << separator;

int elements[] = { 10, 20, 30, 40, 50, 60, 40 };
string delim = " - ";

for_each(elements, elements + 7, bind2nd(ptr_fun(print), delim));


10 - 20 - 30 - 40 - 50 - 60 - 40 -

About ptr_fun, this site says:

This function and the related types are deprecated as of C++11 in favor of the more general std::function and std::ref, both of which create callable adapter-compatible function objects from plain functions.

Can someone rewrite the example above without ptr_fun and with the functions recomended for C++11?

Thank you

Answer Source

The most C++11 way would probably be to use a lambda (or a ranged for)

for_each(elements, elements + 7, [&delim](int val){ print(val, delim); });


ranged for:

for(int x : elements)
    print(x, delim);


You could use std::bind:

for_each(elements, elements + 7, bind(print, placeholders::_1, delim));


But in this case, you could rewrite the whole thing as

copy(elements, elements + 7, ostream_iterator<int>(cout, delim.c_str()));


If you absolutely want to use std::function, you can modify the above examples to do so:

for_each(elements, elements + 7, function<void(int)>([&delim](int val){ print(val, delim); }));

for_each(elements, elements + 7, function<void(int)>(bind(print, placeholders::_1, delim)));

It is pretty pointless unless you need type-erasure, though.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download