Boost logo

Boost Users :

From: Alan M. Carroll (amc_at_[hidden])
Date: 2005-08-26 16:24:36

Here's some code I whipped out that does what you want, although I'm sure it could be done better (it was an interesting learning exercise, though)

# include <boost/mpl/if.hpp>
# include <boost/mpl/list.hpp>
# include <boost/mpl/empty.hpp>
# include <boost/mpl/front.hpp>
# include <boost/mpl/pop_front.hpp>

// this is the thing we want to call on the types
// We don't put it in the functor so that it can be specialized in multiple places
template < typename T > void complicated_function( int i) {
        std::cout << "i = " << i << "  sizeof = " <<
sizeof (T) << std::endl;

// need this as a simple type so we can pass it to chain
struct functor {
template < typename T > void operator () (int i) const { complicated_function<T>(i); }

// do tail recursion on L using the functor F
template < typename F , typename L > struct chain {
struct tail { void operator () (int i) const { return ; } };
struct main {
void operator () (int i) const {
                          F f;
operator ()<boost::mpl::front<L>::type >(i);
                          chain<F, boost::mpl::pop_front<L>::type>()(i);
void operator () (int i) const {
                          tail, main
                 >::type ()(i);

// A list of types to use
typedef boost::mpl::list< int, double , char , std::string> the_list;

// demonstrate that we're calling complicated_function for each type in the list
void mpl_test() {
         chain<functor, the_list>()(17);

At 11:21 AM 8/26/2005, you wrote:

I would like to be able to write code like this:

    int i;
    for F in LIST_OF_TYPES

where this code is inside some other function which is inside a class
templatized over LIST_OF_TYPES.  Given the lack of nested functions and
classes in C++ functions, am I correct in thinking that it's impossible
to do this sort of thing inside another function?

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at