2011-09-20 57 views
4

升級到更新的編譯器並解決編譯器錯誤時,我意識到boost::fusion::for_each要求傳入的函數對象具有運算符const。從Boostboost :: fusion :: for_each中的函數對象與std :: for_each不同

實施例:

struct increment 
{ 
    template<typename T> 
    void operator()(T& t) const 
    { 
     ++t; 
    } 
}; 
... 
vector<int,int> vec(1,2); 
for_each(vec, increment()); 

這具有當然沒有改變。我沒有意識到它與std::for_each不同,它不要求運營商爲const

struct increment 
{ 
    template<typename T> 
    void operator()(T& t) // no const here!!! 
    { 
     ++t; 
    } 
}; 
std::vector<int> numbers; 
std::for_each(numbers.begin(), numbers.end(), increment()); 

是否有任何明顯的理由要求const?我顯然不能改變這一點,但我想明白爲什麼這兩個不同。

感謝您的任何見解和解釋!

回答

1

爲了防止函子的內部狀態發生變化,可能需要使用constness,因爲operator()調用的順序沒有爲每個元素依次定義。所以,後續的呼叫不應該依賴於對方。

+0

看起來像直覺,但它是有道理的;-) – Seb

+0

你有一個參考,它說訂單是不確定的嗎? – murrekatt

+0

@murrekatt不,我不知道。但是[文檔](http://www.boost.org/doc/libs/1_47_0/libs/fusion/doc/html/fusion/algorithm/iteration/functions/for_each.html)也沒有提到任何嚴格的通話順序。還有一個[郵件主題](http://lists.boost.org/boost-users/2007/03/26355.php),您可能會感興趣 - 主要想法是關於性能優化。 –

相關問題