Boost logo

Boost Users :

Subject: [Boost-users] [fusion] clarification on stateful unary function objects
From: Matthias Vallentin (vallentin_at_[hidden])
Date: 2010-02-28 18:37:42


Hi there,

While trying to use a stateful unary function objects, I stumbled over
and old discussion from 2007 [1]. From the current Fusion documentation,
I understand that the functor passed to the for_each algorithm must
satisfy the Regular Callable Object concept. I presume that regularity,
which I understand as replacing inputs with equal objects results in
equal outputs, here implies that operator()(T& x) must be const. In
other words, mutable function objects are not supported. As pointed out
in [1], it is of course possible to bypass this restriction by defining
the state that needs to changed as mutable.

I was wondering if this is still the correct way to deal with mutable
function objects, as illustrated in the small example below:

    #include <iostream>
    #include <string>
    #include <boost/bind.hpp>
    #include <boost/fusion/include/algorithm.hpp>
    #include <boost/fusion/include/container.hpp>

    struct container
    {
        struct printer
        {
            template <typename T>
            void operator()(T& x) const
            {
                std::cout << ++i << ": " << x << std::endl;
            }

            mutable unsigned i;
        };

        template <typename T>
        void write(const T& row)
        {
            boost::fusion::for_each(row, printer());
        }
    };

    int main()
    {
        int i = 42;
        unsigned j = 7;
        std::string s = "foo";

        container c;
        c.write(boost::fusion::vector_tie(i, j, s));

        return 0;
    }

   Matthias

[1] http://lists.boost.org/boost-users/2007/03/26338.php

-- 
Matthias Vallentin
vallentin_at_[hidden]
http://www.icir.org/matthias

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net