[英]using c++11 placeholders as lambdas?
While experimenting with C++11 new features, I discovered that the std::placeholders::_1 can't be directly used as lambdas: 在尝试使用C ++ 11新功能时,我发现std :: placeholders :: _ 1不能直接用作lambdas:
#include <algorithm>
#include <functional>
// #include <boost/lambda/lambda.hpp>
using namespace std;
// using boost::lambda::_1;
using std::placeholders::_1;
int main()
{
int a[] = {1,2,3,4,5};
transform(a, a+5, a, _1 * 2);
}
Clang 3.3 error: Clang 3.3错误:
tmp $ clang -std=c++11 -stdlib=libc++ -lc++ test.cpp
test.cpp:16:27: error: invalid operands to binary expression ('__ph<1>' and 'int')
transform(a, a+5, a, _1 * 2);
If I change it to use Boost's version it compiles fine. 如果我改变它以使用Boost的版本它编译得很好。
Why this doesn't work with the standard version? 为什么这不适用于标准版本? Is there a way to make it work or must I use an ugly lambda here? 有没有办法使它工作或者我必须在这里使用丑陋的lambda?
transform(a, a+5, a, [](int i){return i*2;});
Boost actually has a number of _1
placeholders. Boost实际上有很多_1
占位符。 Those from Boost.Bind (which were more or less incorporated into C++11), those from Boost.Lambda, and even those from Lambda's successor Boost.Phoenix. 来自Boost.Bind的那些(或多或少被并入C ++ 11),来自Boost.Lambda的那些,甚至来自Lambda的继任者Boost.Phoenix的那些。
The Lambda and Phoenix versions are the only placeholders that can be used to create functors by themselves. Lambda和Phoenix版本是唯一可用于创建仿函数的占位符。 The Boost.Bind _1
placeholders cannot, and that's what were standardized. Boost.Bind _1
占位符不能,而且这是标准化的。 Lambda and Phoenix are ways to turn an expression into a function; Lambda和Phoenix是将表达式转换为函数的方法; Bind is simply a function binding and argument adjustment system. 绑定只是一个函数绑定和参数调整系统。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.