views:

55

answers:

1

I'd like a function, or function object, that can generate a permutation of its inputs with the permutation specified at compile time. To be clear, I am not looking to generate all of the permutations, only a specific one. For instance, permute<1,4,3,2>( a, b, c, d ) would return (a,d,c,b). Obviously, it is straightforward to do this with a permutation of a specific length, e.g. 2, like this

#include <boost/tuple.hpp>
template< unsigned a, unsigned b>
struct permute {
    template< class T >
    boost::tuple< T, T > operator()( T ta, T tb ) {
        boost::tuple< T, T > init = boost::make_tuple( ta, tb );
        return boost::make_tuple( init.get< a >(), init.get< b >() );
    }
};

But, how would I go about doing this for an arbitrary length permuation? Also, is there a cleaner way of writing the above code? Yes, the above code is not restricted to making permutations as permute<2,2>(a,b) is allowed, but I don't see that as a flaw. However, can it be restricted to only allowing actual permutations?

A: 

C++0x provides variadic templates, which you should be able to use to handle an arbitrary length permutation. They were added specifically because the current version of C++ doesn't have a clean way of dealing with this kind of problem.

Jerry Coffin
You're absolutely correct, and considering I knew about them prior to posting, I guess I shouldn't have asked in the first place. But, since you answered, you get the credit.
rcollyer