在 C++11 和/或 C++1y 中:
假设给我一个带有非类型参数包的模板:
template<int...>
void f();
我正在编写另一个模板来实例化它:
template<int... x>
void g()
{
???
f<???>();
}
我希望 g 按排序顺序用 x 实例化 f。
即:
g<4,7,2,9,3,7>();
应该调用:
f<2,3,4,7,7,9>();
这可以吗?如果是这样,最有效的方法是什么(直到常数因素)?
最佳答案
所有这些答案都是令人沮丧的 C++11... 大量模板元编程涌现。
这是使用普通排序 constexpr 函数的 C++14 解决方案。
(使用 clang + libc++ trunk 编译和运行,std=c++1y)
#include <utility>
#include <iostream>
template<int... x>
void f()
{
constexpr int x_array[] = {x...};
for(int i = 0; i < sizeof...(x); i++)
std::cout << x_array[i] << " ";
std::cout << std::endl;
}
template <typename T, int N>
struct ConstArray
{
T data[N];
constexpr T& operator[](int i){return data[i];}
constexpr const T& operator[](int i) const {return data[i];}
};
template<int... x>
constexpr auto bubble_sort_best_sort()
{
constexpr int N = sizeof...(x);
ConstArray<int, N> a = {x...};
for (int i = 0; i < N - 1; i++)
{
for (int j = 0; j < N - i - 1; j++)
{
if (a.data[j] > a.data[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1]= temp;
}
}
}
return a;
}
template<int... x, int...i>
void g_imp(std::integer_sequence<int, x...>,
std::integer_sequence<int, i...> )
{
constexpr auto array_sorted = bubble_sort_best_sort<x...>();
f<array_sorted[i]...>();
}
template<int... x>
void g()
{
auto seq = std::integer_sequence<int, x...>();
auto idx = std::make_integer_sequence<int, sizeof...(x)>();
g_imp(seq, idx);
}
int main()
{
g<4, 7, 2, 9, 3, 7>();
return 0;
}
我们被迫定义一个自定义的ConstantArray而不是使用std::array,这有点奇怪。
如果只有它的“T& operator[]”成员是 constexpr,那么 std::array 在这里可能没问题。我检查了最新的草稿,但仍然不是这样,但我不明白为什么。
关于c++ - 在 C++11 或 C++1y 中对非类型模板参数包进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19209228/