c++ - 排列参数包中的参数

标签 c++ c++11 template-meta-programming

我有两个结构

template <int ... values>
struct foo {}

template <int ... values>
struct lists {} 

我想要一个函数 bar这需要 listsfoo并排列 foo 的参数返回另一个 foo

another_foo bar(lists<0,3,1,2>, foo<4,5,6,7>)

我想要 another_foo 的类型成为foo<4,7,5,6>所以基本上根据另一个参数对一个参数进行排序。我还希望该函数可以使用列表中的任意参数,而不必作为 foo 的索引。参数,例如

another_foo bar(lists<20,12,21,13>, foo<4,5,6,7>)

我要another_foo成为 foo<6,4,7,5> 的类型别名.在这种情况下,lists<20,12,21,13>基本上是 lists<2,0,3,1> 的另一个版本就优势而言,这就是元素的排列方式。我该怎么做?

谢谢

最佳答案

template<size_t N>
constexpr size_t count_less(const int (&seq)[N], int i, size_t cur = 0) {
    return cur == N ? 0
                    : (count_less(seq, i, cur + 1) + (seq[cur] < i ? 1 : 0));
}

template<class List, class Foo, class Seq>
struct meow;

template<int... ls, int... fs, size_t... ss>
struct meow<lists<ls...>, foo<fs...>, std::index_sequence<ss...>>{
    constexpr static int lst[] = { ls... };
    constexpr static int fvals[] = {fs...};
    using type = foo<fvals[count_less(lst, lst[ss])]...>;
};

template<int... ls, int... fs>
auto bar(lists<ls...>, foo<fs...>)
    -> typename meow<lists<ls...>, foo<fs...>, 
                     std::make_index_sequence<sizeof...(ls)>>::type;

关于c++ - 排列参数包中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37287695/

相关文章:

c++ - 堆损坏 - Vector push_back

c++ - 如何通过参数包传递引用?

C++ 段错误有时但

c++ - 使用模板元编程 [C++11] 对整数列表进行操作

c++ - 检查模板参数是否在同质参数包中出现两次以上

c++ - 如何将 C 库用于 Arduino 代码

c++ - 将 glUniform 函数作为参数传递 (C++)

c++ - 在 Qt 中使用 += 运算符时出错

c++ - 为什么 C++ 11 将 operator bool 添加到 ios 类

c++ - 如何在编译时检测类型是否为 lambda 表达式?