开发者

How do I use boost.lambda with boost.range to select from a container?

In C# with Linq, I would write:

myContainer.Select(o => o.myMember);

I'm not sure what the syntax should be for C++/lambda/range. I'm simply trying to adapt a container of some object type to a container of strings so that I can pass it to boost::algorithm::join. I tried something like:

using namespace boost::adaptors;
using namespace boost::lambda;
string result = join(myContainer | transformed(_1.myMember), ", ");

But o开发者_高级运维bviously that doesn't work or I wouldn't be here. ;)

I'm using transformed after reading: http://www.boost.org/doc/libs/1_43_0/libs/range/doc/html/range/reference/adaptors/reference/transformed.html

I want to use a lambda instead of a separate function for brevity.


operator. is not overloadable, thus it can never do anything sensible on a placeholder.


Boost.Lambda (and Boost.Phoenix v1 and v2, which were based on Boost.Lambda) implements its own result_of protocol rather than the TR1 result_of protocol, so Boost.Lambda functors will not work with anything using boost::result_of or std::tr1::result_of (as Boost.Range does).

That said, Boost.Phoenix v3, slated to be released in Boost 1.47, is the official replacement for Boost.Lambda and does implement the TR1 result_of protocol, and so does play nice with boost::result_of (and consequently Boost.Range).

Your options are to either use Boost.Bind instead of Boost.Lambda, in which case the following is valid:

transformed(bind(&myObjectType::myMember, _1))

or you can use Boost.Phoenix v3 instead of Boost.Lambda (either get Boost.Phoenix out of trunk now or wait for Boost 1.47), in which case the Boost.Bind syntax is valid, as well as the following alternative:

transformed(_1->*&myObjectType::myMember)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜