[英]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: 我正在尝试学习C ++ 11的新功能,我有这个代码:
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: 关于ptr_fun, 这个网站说:
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.
从C ++ 11开始,不推荐使用此函数和相关类型,而使用更通用的std :: function和
std :: ref ,这两者都从普通函数创建可调用的适配器兼容函数对象。
Can someone rewrite the example above without ptr_fun and with the functions recomended for C++11? 有人可以在没有ptr_fun和C ++ 11推荐的函数的情况下重写上面的例子吗?
Thank you 谢谢
The most C++11 way would probably be to use a lambda (or a ranged for) 大多数C ++ 11方式可能是使用lambda(或范围为)
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
: 你可以使用
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: 如果你绝对想要使用
std::function
,你可以修改上面的例子来做到这一点:
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. 你不在这里使用
std::function
。 It makes no sense. 这个不成立。
std::function<...>
is a type that many callable objects can be converted to . std::function<...>
是一种可以转换为许多可调用对象的类型。 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
. 它没有任何意义创建
std::function
暂时并立即把它传递给一个标准的算法类似std::for_each
。 Standard algorithms generally accept all kinds of callable objects, including any you could create std::function
from . 标准算法通常接受所有类型的可调用对象,包括任何可以创建
std::function
的对象 。 So std::function
would be nothing but a redundant middleman. 所以
std::function
只不过是一个多余的中间人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.