如何在编译时交换可变参数模板的两个参数? [英] How to swap two parameters of a variadic template at compile time?
问题描述
我正在尝试在编译时交换可变参数模板的两个参数:
I'm trying to swap two parameters of a variadic template at compile time :
template<int...Numbers>struct sequence{};
template<size_t first,size_t second>
struct Swap_Pair
{
const static size_t First = first;
const static size_t Second = second;
};
template <int...Numbers,class swap_pair>
struct Swap_Data
{
static std::array<int, sizeof...(Numbers)> data_;//How to swap Numbers base on the pair and store it in data_ ?
};
用例应为:
sequence<1, 2, 3, 4, 5, 6> array;
auto result = Swap_Data < array, Swap_Pair<2, 5> > ::data_;
//result is now std::array which contains 1 2 6 4 5 3
我不知道写Swap_Data
的正确方法是什么.
I can't figure out what is the proper way of writing Swap_Data
.
我该如何进行递归交换,以交换可变参数并在编译时转换为std :: array?
And how can I make a recursive swap for swapping variadic parameters and converting into std::array at compile time ?
推荐答案
我在评论中发布的链接是我自己对元函数的std::bind()
类元函数的实现.
The link I posted on the comment is my own implementation of a std::bind()
-like metafunction for metafunctions.
我所做的是将bind
调用参数从其值(一个值或一个占位符)转换为一个值或该占位符表示的值.
What I did is to transform the bind
call parameters from its value (A value or a placeholder) to a value, or the value represented by that placeholder.
在您的情况下,您可以尝试类似的方法:将序列从占位符(传递给swap的值)映射到序列的相应值.像这样:
In your case you could try a similar approach: Map the sequence from placeholders (The values passed to swap) to the corresponding values of the sequence. Something like:
template<std::size_t I>
struct placeholder{};
using _1 = placeholder<0>;
... //More placeholder aliases
template<typename SEQ , typename... PLACEHOLDERS>
struct swap;
template<std::size_t... Is , std::size_t... Ps>
struct swap<sequence<Is...>,placeholder<Ps>...>
{
template<typename PLACEhOLDER>
struct transformation;
template<std::size_t I>
struct transformation<placeholder<I>>
{
static constexpr const std::size_t result = get<sequence<Is...>,I>::value;
};
using result = map<transformation,sequence<Is...>>;
};
map
是类似于std::transform()
的元函数(非常容易编写),而get
是检索序列的第I个元素的元函数(也很容易).
Where map
is a metafunction similar to std::transform()
(Very easy to write), and get
a metafunction which retrieves the Ith element of a sequence (Easy too).
这可以通过以下方式使用:
This could be used on this way:
using swapped = typename swap<sequence<1,2,3>,_3,_2,_1>::result; //swapped is sequence<3,2,1>
这篇关于如何在编译时交换可变参数模板的两个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!