模板实现编译时冒泡排序
看到特首写了个编译时的归并,感觉挺好玩,写了个冒泡试试,第一次用模板写这种东西,见笑了(
#include
#include
#include
using namespace std;
template struct Vals {};
template struct ValueAt;
template struct ValueAt>
{
constexpr static int val = ValueAt>::val;
};
template struct ValueAt<0, Vals>
{
constexpr static int val = val0;
};
template struct Combine;
template struct Combine, Vals>
{
using type = Vals;
};
template struct SwapValue;
template struct SwapValue>
{
using type = typename Combine, typename SwapValue>::type>::type;
};
template struct SwapValue<0, Vals>
{
using type = typename Combine, typename Combine, Vals>::type>::type;
};
template struct SwapValue<0, Vals>
{
using type = Vals;
};
template struct BubbleSort
{
using type = typename conditional_t<(ValueAt::val > ValueAt::val),
BubbleSort::type>,
BubbleSort>::type;
};
template struct BubbleSort<1, 1, Vals>
{
using type = Vals;
};
template struct BubbleSort>
{
using type = Vals;
};
template struct BubbleSort>
{
using type = typename BubbleSort>::type;
};
template struct Sort
{
using type = typename BubbleSort<0, 1, T>::type;
};
template void print(Vals)
{
static constexpr auto vs = { vals... };
copy(begin(vs), end(vs), ostream_iterator(cout, " "));
endl(cout);
}
int main()
{
print(Sort>::type());
print(Sort>::type());
print(Sort>::type());
return 0;
}
代码本身很简单,就是冒泡的思路,递归 j 的终止条件应该还可以优化一下