c++boostboost-foreach

Redefine BOOST_FOREACH macro safely


I have the following macro:

#define FOREACH(decl, c) BOOST_FOREACH(decl, std::make_pair((c).begin(), (c).end()))

(I am using this macro, because my containers do not implement the mutable iteration API.)

The problem with it, is that c is evaluated twice.

My question is can this macro be fixed so that:

  1. c is evaluated at most once
  2. Any local variables created in order to satisfy the first condition live within the respective foreach scope only.

Solution

  • You could use an inline helper function.

    #define FOREACH(decl, c) BOOST_FOREACH(decl, pair_helper(c))
    
    template <typename T>
    inline std::pair<typename T::iterator, typename T::iterator> pair_helper (T c) {
        return std::make_pair(c.begin(), c.end());
    }