Boost logo

Boost :

From: Aleksey Gurtovoy (alexy_at_[hidden])
Date: 2001-06-27 13:44:43


Beman Dawes wrote:
> * Indexing and naming issues:
>
> (It's hard from reading the back postings to see the final
> resolution on this. Was the decision that the usage was
> index-like and so should be 0 based, or name-like and
> so should be 1 based?
 
I can imagine someone writing a compile-time loop, iterating through
(subrange of) tuple elements, e.g. printing some of them of particular type:

template<typename T> struct printer {
  static void print(T const& t) {
    std::cout << t;
  }
};

struct null_printer {
  template<typename T> static void print(T const&) {}
};

template<typename T>
struct print_tuple_element {
  template<class N> struct body {
    typedef print_tuple_element next_statement;

    template<class Tuple>
    static inline void execute(Tuple const& t) {
      typedef typename boost::tuple_element_type<N::value, Tuple>::type
element_type;

      typedef typename boost::mpl::select_type<
          boost::is_same<element_type, T>::value
        , printer<T>
        , null_printer
>::type printer_type;
      
      printer_type::print(boost::get<N::value>(t));
    }
  };
};

int main() {
  namespace mpl = boost::mpl;
  typedef mpl::for_loop< mpl::int_value<0>, mpl::less_than<5>, mpl::next<>
                       , mpl::loop_variable_accessor<
print_tuple_element<int> >
> printing_loop;
                    
  printing_loop::execute(boost::make_tuple(5, std::string("text"), 7, 3.14,
9));
}

Currently this will fail, because I wrote

for_loop< int_value<0>, less_than<5>, ...

instead of

for_loop< int_value<1>, less_equal_to<5>, ...

Personally, I would hate to remember to write 1-based loops at compile time
and 0-based ones everywhere else. Just my .02 cents.

Aleksey


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk