使用c++11占位符作为lambda

using c++11 placeholders as lambdas?

本文关键字:lambda 占位符 c++11 使用      更新时间:2023-10-16

在试验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错误:
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);

如果我把它改为使用Boost的版本,它编译得很好。

为什么这个不能在标准版本中工作?有办法让它工作吗,还是我必须在这里使用一个丑陋的lambda ?

transform(a, a+5, a, [](int i){return i*2;});

Boost实际上有许多_1占位符。那是Boost的。Bind(或多或少被合并到c++ 11中),这些来自Boost。Lambda,甚至是Lambda的继任者Boost.Phoenix。

Lambda和Phoenix版本是唯一的占位符,可以用来自己创建函函数。的提振。Bind _1占位符不能,这就是标准化的原因。Lambda和Phoenix是将表达式转换为函数的方法;Bind只是一个函数绑定和参数调整系统。