2011-09-20 95 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),您可能会感兴趣 - 主要想法是关于性能优化。 –