2016-02-24 54 views
1

我想將a中包含的所有整數複製到b升壓範圍for_each,bind,copy和back_inserter組合失敗

#include <vector> 
#include <iterator> 
#include <boost/bind.hpp> 
#include <boost/range/algorithm/for_each.hpp> 
#include <boost/range/algorithm/copy.hpp> 
void test() 
{ 
     std::vector<std::vector<int> > a; 
     std::vector<int> b; 
     boost::for_each(a, boost::bind(boost::copy, _1, std::back_inserter(b))); 
} 

看起來很簡單。我想要一個兼容C++ 98的班輪。

爲什麼不編譯? 我有一長串關於boost::bind的錯誤列表,我不明白,而且它是多頁多長。

錯誤C2780:

錯誤開頭「的boost :: _雙:: bind_t < _bi :: dm_result ::類型,提振:: _ MFI :: DM,_bi :: list_av_1 ::類型> boost :: bind(MT :: *,A1)':期望2個參數 - 3提供

+0

請定義「不起作用」,崩潰?不會編譯?如果你有錯誤信息,請給它。 – Borgleader

+1

它'不起作用',因爲它有'一些錯誤'。如果你更具體,你不會得到更好的答案。 – SergeyA

+0

對不起,添加更多信息 – lars

回答

1

這裏有一個直接相關的問題:Can I use (boost) bind with a function template?。該問題中的錯誤消息是相同的,並且問題不同之處在於它們的模板函數不是庫函數。

這裏的訣竅是,你打算綁定一個模板函數boost::copy<>(),根據鏈接的問題,它是不可能的,因爲模板函數必須實例化才能作爲函數指針傳遞。這也表示爲here,章節「綁定模板函數」。所以,不幸的是,你需要求助於一個相當長的結構,它可以與使用typedef稍微縮短(因爲你在C++ 98,沒有decltype都是可用的):

int main() 
{ 
     typedef std::vector<int> IntVec; 
     std::vector<IntVec> a; 
     IntVec b; 
     boost::for_each(a, 
      boost::bind(boost::copy<IntVec, 
      std::back_insert_iterator<IntVec> >, _1, std::back_inserter(b))); 
}