通过模板生成排列
我想要一个函数或函数对象,它可以使用编译时指定的排列生成其输入的排列。需要明确的是,我并不希望生成所有排列,而只是生成一种特定排列。例如,permute<1,4,3,2>(a, b, c, d)
将返回 (a,d,c,b)
。显然,使用特定长度(例如 2)的排列来做到这一点很简单,就像这样
#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 >() );
}
};
但是,我将如何针对任意长度的排列执行此操作?另外,是否有更清晰的方式来编写上述代码?是的,上面的代码不限于进行排列,因为允许 permute<2,2>(a,b)
,但我不认为这是一个缺陷。但是,是否可以限制为只允许实际排列?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C++0x 提供了可变参数模板,您应该能够使用它来处理任意长度的排列。它们是专门添加的,因为当前版本的 C++ 没有一个干净的方法来处理此类问题。
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.