2011-08-23 60 views
4

我想使用boost::bind和STL與boost::tuple,但每次我嘗試編譯時出現以下錯誤。boost :: bind不能使用boost :: tuple :: get <N>()

 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) 
        ) 
      ); 
+1

什麼是「eth_array」? 'boost'命名空間中沒有'獲取'某些東西嗎?不是這個'eth_array'命名空間/類? –

+0

auch ..我在複製代碼時已更改。在上面的示例中已修復。 –

回答

8

get函數具有多個模板參數:除索引外,它還參數化元組的內容(cons的頭部和尾部)。

因此,get<0>不是模板的實例;您需要提供額外的參數:

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

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

然而,這仍然無法工作,因爲get超載(const和non-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不相處得很好......

+0

嗨,呂克!這是一個超級迴應。從來沒有太多的洞察boost :: tuple +模板! –

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) 
      ) 
    ); 
} 
+0

嗨AndrzejJ。你是對的我的意思是v + = boost :: make_tuple(10,23.4),boost :: make_tuple(12,24.4); (我做了一些混亂,我修復了我的代碼,使其更具可讀性)。 的一點是,升壓::綁定(eth_array ::獲得<0>,_1)仍然沒有在的std :: for_each的工作,即使使用&。還是隻爲ARG <1> –

+0

你不必在你的代碼中定義的eth_array類型,但是當我用_array我得到了它的編譯和運行。我編輯了我的答案,包括編譯在我的系統上的整個main()函數。 – AndrzejJ