【问题标题】:How to swap two parameters of a variadic template at compile time?如何在编译时交换可变参数模板的两个参数?
【发布时间】:2014-08-01 10:23:44
【问题描述】:

我试图在编译时交换可变参数模板的两个参数:

 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 的正确方法是什么。

如何进行递归交换以在编译时交换可变参数并转换为 std::array ?

【问题讨论】:

  • 类似int swapped_arr[] = { unswapped_arr[N == swap_pair::First ? swap_pair::Second : N == swap_pair::Second ? swap_pair::First : N]... }; 的地方有一个未交换元素的数组;你也可以使用一些 integer_sequenceget&lt;N&gt;(seq) 函数。

标签: c++ templates c++11 metaprogramming variadic-templates


【解决方案1】:

我在评论中发布的链接是我自己实现的类似std::bind() 的元函数元函数。

我所做的是将bind 调用参数从它的值(一个值或一个占位符)转换为一个值,或由该占位符表示的值。

在您的情况下,您可以尝试类似的方法:将序列从占位符(传递给交换的值)映射到序列的相应值。比如:

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 个元素的元函数(也很简单)。

可以这样使用:

 using swapped = typename swap<sequence<1,2,3>,_3,_2,_1>::result; //swapped is sequence<3,2,1>

【讨论】:

    猜你喜欢
    • 2018-02-16
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多