Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

#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:

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.

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?

transform(a, a+5, a, [](int i){return i*2;});
like image 834
ogoid Avatar asked Jan 19 '13 20:01

ogoid


1 Answers

Boost actually has a number of _1 placeholders. 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.

The Lambda and Phoenix versions are the only placeholders that can be used to create functors by themselves. The Boost.Bind _1 placeholders cannot, and that's what were standardized. Lambda and Phoenix are ways to turn an expression into a function; Bind is simply a function binding and argument adjustment system.

like image 73
Nicol Bolas Avatar answered Sep 28 '22 05:09

Nicol Bolas