开发者

Generating permutations via templates

开发者 https://www.devze.com 2023-01-05 17:35 出处:网络
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

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消