Boost logo

Boost :

From: Dan Mcleran (dan.mcleran_at_[hidden])
Date: 2003-04-07 17:46:43


>I haven't been able to find any utility to any sensible metaprogramming
>with boost::tuples's. In particular, I'm interested in having one of the
>
>following (either will do):
>
>1. Write a metaprogram that reverses a boost::tuple, i.e a construct
>say reverse such that
>
>reverse<Tuple>::type
>
>is a tuple containing the same elements as Tuple but in reverse order.

You can do this quite easily with partial template specialization. I hve
defined a class called reverse_tuple, which calls another class
reverse_tuple_impl (for ease of use). I use partial template specialization
on the length of the tuple to form the reversed typedef. You would need to
write as many specializations as you wanted to account for (similar to
Loki::TypeList). hope this helps.

I compiled and checked this out on Dev C++ 4.9.7.0:

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

using namespace boost::tuples;

template<int N,class T>
struct reverse_tuple_impl{};

template<class T>
struct reverse_tuple_impl<3,T>
{
 typedef typename boost::tuple<typename element<2,T>::type,typename
element<1,T>::type,typename element<0,T>::type> type;
};

template<class T>
struct reverse_tuple
{
 typedef typename reverse_tuple_impl<length<T>::value,T>::type type;
};

typedef boost::tuple<int,long,double> t1;
typedef reverse_tuple<t1>::type t2;

int main(int argc, char *argv[])
{
 using namespace std;

 cout<<"In tuple<int,long,double>:"<<endl;
 cout<<typeid(element<0,t1>::type).name()<<endl;
 cout<<typeid(element<1,t1>::type).name()<<endl;
 cout<<typeid(element<2,t1>::type).name()<<endl;

 cout<<"In reversed tuple:"<<endl;
 cout<<typeid(element<0,t2>::type).name()<<endl;
 cout<<typeid(element<1,t2>::type).name()<<endl;
 cout<<typeid(element<2,t2>::type).name()<<endl;

 system("PAUSE");
 return 0;
}


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