ogo*_*oid 7 c++ lambda boost placeholder c++11
在尝试使用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);
}
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
如果我改变它以使用Boost的版本它编译得很好.
为什么这不适用于标准版本?有没有办法使它工作或者我必须在这里使用丑陋的lambda?
transform(a, a+5, a, [](int i){return i*2;});
Run Code Online (Sandbox Code Playgroud)
Boost实际上有很多_1占位符.来自Boost.Bind的那些(或多或少被并入C++ 11),来自Boost.Lambda的那些,甚至来自Lambda的继任者Boost.Phoenix的那些.
Lambda和Phoenix版本是唯一可用于创建仿函数的占位符.Boost.Bind _1占位符不能,而且这是标准化的.Lambda和Phoenix是将表达式转换为函数的方法; 绑定只是一个函数绑定和参数调整系统.