4

我正在尝试将boost::bindSTL 与 一起使用boost::tuple,但每次尝试编译时都会出现以下错误。

      error: call of overloaded ‘bind(<unresolved overloaded function type>, 
      boost::arg<1>&)’ is ambiguous

你知道我在这里做错了什么,为什么只是为了boost::arg<1>

谢谢AFG

    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <cstdio>
    #include <boost/tuple/tuple.hpp>
    #include <boost/assign.hpp>
    #include <boost/bind.hpp>

    int main( int argc, const char** argv ){


            using namespace boost::assign;
            typedef boost::tuple< int, double > eth_array;

            std::vector< eth_array > v;
            v+= boost::make_tuple( 10,23.4), boost::make_tuple( 12,24.4) );
            std::for_each( v.begin()
                    , v.end()
                    , boost::bind<int>(
                            printf
                            , "%d-%f"
                            , boost::bind( eth_array::get<0>, _1 )
                            , boost::bind( eth_array::get<1>, _1 )
                     )
            );
4

2 回答 2

8

get函数有多个模板参数:除了索引之外,还对元组的内容(的头部和尾部cons)进行了参数化。

因此,get<0>不是模板的实例化;您需要提供其他参数:

typedef eth_array::head_type head;
typedef eth_array::tail_type tail;

... get<0, head, tail> ...

但是,这仍然不起作用,因为get它被重载(const 和非 const 版本),所以你需要明确说明你想要的重载。为此,您需要使用具有正确类型的函数指针:

// const version of get, which takes and returns const references
int const & (*get0)( boost::tuples::cons<head, tail> const & ) = 
    boost::get<0, head, tail>;
double const & (*get1)( boost::tuples::cons<head, tail> const & ) = 
    boost::get<1, head, tail>;

现在您可以在绑定表达式中使用这些函数指针:

std::for_each( v.begin(),
               v.end(),
               boost::bind<int>(
                   printf,
                   "%d-%f",
                   boost::bind( get0, _1 ),
                   boost::bind( get1, _1 )
               )
);
// outputs 10-23.40000012-24.400000

如您所见,重载的函数模板并bind不能很好地相处......

于 2011-08-23T10:08:21.993 回答
1

这里有几个问题: eth_array没有定义,我猜应该是_array。

v+= ( boost::make_tuple( 10,23.4) )( boost::make_tuple( 12,24.4) );

在这里,您试图将元组调用为函数?也许你尝试过类似的东西:

v+=boost::make_tuple( 10,23.4);
v+=boost::make_tuple( 12,24.4);

最后,似乎是什么导致了您描述的问题:

boost::bind( eth_array::get<0>, _1 )

您应该尝试使用函数指针而不是原始函数名称:

boost::bind( &eth_array::get<0>, _1 )

我要编译和运行的 main() 的完整主体:

int main( int argc, const char** argv ){

    using namespace boost::assign;
    typedef boost::tuple< int, double > _array;

    std::vector< _array > v;
    v+=boost::make_tuple( 10,23.4);
    v+=boost::make_tuple( 12,24.4);
    std::for_each( v.begin()
            , v.end()
            , boost::bind<int>(
                    printf
                    , "%d-%f\n"
                    , boost::bind( &_array::get<0>, _1 )
                    , boost::bind( &_array::get<1>, _1 )
             )
    );
}
于 2011-08-23T08:43:12.947 回答