Saturday, February 6, 2010

iterating a boost::tuple

The boost::tuple class is a subclass of boost::tuples::cons, which is
a list type structure that can be recursed in a manner similar to LISP
lists. The following code is an example of how to accomplish this.


#include <boost/tuple/tuple.hpp>
#include <iostream>

template < typename X >
void print_data(X const& x)
{
std::cout << " Type of elem: " << typeid(X).name() << std::endl;
std::cout << "Value of elem: " << x << std::endl;
}

template < typename H, typename T >
struct do_recurse
{
static void apply(boost::tuples::cons<H,T> const& c)
{
typedef boost::tuples::cons<H,T> current_cons;
typedef typename current_cons::tail_type tail_cons;
typedef typename tail_cons::head_type tail_head;
typedef typename tail_cons::tail_type tail_tail;

print_data(c.get_head());
do_recurse<tail_head, tail_tail>::apply(c.get_tail());
}
};

template < typename H >
struct do_recurse<H, boost::tuples::null_type>
{
static void apply(boost::tuples::cons<H,boost::tuples::null_type> const& c)
{
std::cout << " Type of last elem: " << typeid(H).name() << std::endl;
std::cout << "Value of last elem: " << c.get_head() << std::endl;
}
};

template < typename H, typename T >
void recurse(boost::tuples::cons<H,T> const& c)
{
do_recurse<H,T>::apply(c);
}


int main(int argc, char* argv[])
{
using namespace boost::tuples;
tuple<int, char, double> t(42,'A',3.14);

recurse(t);

std::cin.get();
return 0;
}

Wrapping the function in a struct is necessary because functions
cannot be partially specialized.

No comments:

Post a Comment