不能转换boost::lambda::placeholder1_type

cannot convert boost::lambda::placeholder1_type

本文关键字:type placeholder1 lambda boost 不能 转换      更新时间:2023-10-16

我正在尝试使用boost::lambda,但我遇到了一个错误,我不知道如何解决。

我感觉这是一个初学者的错误,所以请原谅我的无知(而且,我必须承认,我的懒惰也没有阅读整个boost lambda文档)。

似乎在某些情况下使用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) ) );

任何帮助都将不胜感激,

谢谢

您将延迟执行与立即求值混合在一起:

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

这里,boost::ref(myResults)不懒惰,所以.get()也不懒惰。boost::ref(myResults).get()的类型只是 std::set<long> &,并且该类型的insert成员函数没有接受Boost Lambda占位符的重载。

我不精通Boost Lambda(不再),因为我已经转移到它的后继库Boost Phoenix。这里是一个1对1的翻译与修复: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

我建议查看Phoenix函数适配,以避免bind表达式:

  • http://www.boost.org/doc/libs/1_55_0/libs/phoenix/doc/html/phoenix/modules/function/adapting_functions.html