4

While upgrading to a newer compiler and resolving compiler errors I realized that boost::fusion::for_each requires that the function object passed in has the operator const.

Example from Boost:

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

This has of course not changed. I didn't realized it's different to std::for_each, which does not require the operator to be 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());

Is there any obvious reason for requiring const? I obviously cannot change that, but I'd like to understand why these two differ.

Thanks for any insights and explanations!

murrekatt
  • 5,961
  • 5
  • 39
  • 63

1 Answers1

1

Constness may be required to prevent internal state changes of the functor, since, the order of the operator() calls is not defined for each element in sequence. So, the consequent calls should not depend on each other.

abyss.7
  • 13,882
  • 11
  • 56
  • 100
  • looks like intuition but it makes sense ;-) – Seb Sep 20 '11 at 13:01
  • Do you have a reference where it says the order is undefined? – murrekatt Sep 20 '11 at 13:14
  • @murrekatt No, I don't. But also, the [documentation](http://www.boost.org/doc/libs/1_47_0/libs/fusion/doc/html/fusion/algorithm/iteration/functions/for_each.html) doesn't mention any strict order of the calls. And there is a [mailing thread](http://lists.boost.org/boost-users/2007/03/26355.php) which may interest you - the main idea is about performance optimizations. – abyss.7 Sep 20 '11 at 17:55
  • @abyss.7: thanks for the mail thread. I believe a for_each means it is a strict order, not the opposite. – murrekatt Sep 20 '11 at 20:30