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));
Output:
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 and , 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
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.
You do not use std::function
here. It makes no sense.
std::function<...>
is a type that many callable objects can be converted to . It makes sense to use this type for a variable or a function argument that should accept a callable object, especially when type erasure is desirable (eg when your function cannot be a template).
It does not make sense to create an std::function
temporary and immediately pass it to a standard algorithm like std::for_each
. Standard algorithms generally accept all kinds of callable objects, including any you could create std::function
from . So std::function
would be nothing but a redundant middleman.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.