无法转换boost :: lambda :: placeholder1_type

时间:2014-05-12 11:15:17

标签: c++ boost boost-lambda

我正在尝试使用boost :: lambda,但我遇到了一个错误,我无法弄清楚如何解决。

我觉得这是一个初学者的错误,所以请原谅我的无知(并且,我不得不承认,我的懒惰是因为没有阅读整个提升lamda文档)。

似乎在某些情况下使用boost :: bind(或者可能是boost :: lambda :: bind?),比boost :: lambda更适合,但我不确定它是否可以在这里应用。我不想为if cond(arg1) arg2.insert(arg1) ;编写单独的函数,因为它会破坏目的;我认为它不会比仿函数好多了。

我正在使用boost 1.35和VC9。错误发生在cond()insert()个致电网站上: “C2664:无法从'boost :: lambda :: placeholder1_type”转换参数1

我在我的cygwin上用g ++复制了这段代码的问题。

#include <boost/function.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/if.hpp>

#include <boost/foreach.hpp>
#include <iostream>
#include <set>

void work(  boost::function<void(long)> doAction ) {
    long results[] = { 2, 5, 4 };
    BOOST_FOREACH( long r, results )
        doAction( r );
}

bool cond( long r ) { return r % 2 == 0 ; }

int main() {
    using namespace boost::lambda;
    std::set<long> myResults;
    work( 
        if_then( cond(_1) , boost::ref(myResults).get().insert(_1) ) );

    BOOST_FOREACH( long r, myResults )
        std::cout << r << "\n";
}

g ++错误:

lambda_test.cpp: In function ‘int main()’:
lambda_test.cpp:21:19: error: cannot convert ‘boost::lambda::placeholder1_type {aka const boost::lambda::lambda_functor<boost::lambda::placeholder<1> >}’ to ‘long int’ for argument ‘1’ to ‘bool cond(long int)’
if_then( cond(_1) , boost::ref(myResults).get().insert(_1) ) );
               ^
lambda_test.cpp:21:60: error: no matching function for call to ‘std::set<long int>::insert(boost::lambda::placeholder1_type&)’
if_then( cond(_1) , boost::ref(myResults).get().insert(_1) ) );

任何帮助将不胜感激,

由于

1 个答案:

答案 0 :(得分:1)

您将延迟执行与即时评估相结合:

boost::ref(myResults).get().insert(_1)

此处boost::ref(myResults)并非懒惰,因此.get()也不是。 boost::ref(myResults).get()的类型只是 std::set<long> &,并且该类型的insert成员函数没有带有Boost Lambda占位符的重载。

我不再精通Boost Lambda(因为我已经搬到了它的继任者库,Boost Phoenix)。这是一对一翻译,包含修正: Live On Coliru

#include <boost/phoenix.hpp>

#include <boost/foreach.hpp>
#include <iostream>
#include <set>

template <typename Action>
void work(  Action doAction ) {
    long results[] = { 2, 5, 4 };
    BOOST_FOREACH( long r, results )
        doAction( r );
}

bool cond( long r ) { return r % 2 == 0 ; }


int main() {
    namespace phx = boost::phoenix;
    using namespace phx::placeholders;

    std::set<long> myResults;
    work( 
        if_(phx::bind(cond, _1)) [ phx::insert(phx::ref(myResults), _1) ] );

    BOOST_FOREACH( long r, myResults )
        std::cout << r << "\n";
}

打印

2
4

我建议看凤凰函数适应,以避免绑定表达式: