C++模板元编程—-快速排序

实现

数据结构定义

，同时对一些类型进行了改名。

```// 数据结构定义
template<int ...>
struct mvector;
typedef mvector<data...> tail_type;
constexpr static std::array<int, 1 + sizeof...(data)> value = {_head, data...};
};
typedef mvector<> tail_type;
constexpr static std::array<int, 1> value = {_head};
};
template<>
struct mvector<> {
constexpr static int head = -1;
typedef mvector<> tail_type;
constexpr static std::array<int, 0> value = {};
};```

在数组前添加一个元素

```// 在数组前增加一个元素
template<int data, typename list>
template<int data, int ...data_list>
typedef mvector<data, data_list...> result_type;
};```

判断

```// 判断，输出一个类型
template<bool, typename T, typename S>
struct m_type_if;
template<typename T, typename S>
struct m_type_if<true, T, S> {
typedef T result_type;
typedef S not_result_type;
};
template<typename T, typename S>
struct m_type_if<false, T, S> {
typedef S result_type;
typedef T not_result_type;
};```

分堆

```// 分堆
template<typename , typename>
struct m_diff;
template<typename _mid, int ...data, int data_head>
typedef _mid mid;
typedef m_diff<_mid, mvector<data...>> next_type;
};
template<typename _mid>
struct m_diff<_mid, mvector<>> {
typedef _mid mid;
typedef m_diff<_mid, mvector<>> next_type;
typedef mvector<> right_type;
typedef mvector<> left_type;
};```

合并

```// 合并
template<typename, typename, typename>
struct combine_result;
template<int ...data_S, int mid, int ...data_T>
struct combine_result<mvector<data_S...>, mvector<mid>, mvector<data_T...>> {
typedef mvector<data_S..., mid, data_T...> result_type;
};```

快速排序的实现

```// 快排
template<typename data>
struct QuickSortWork;
template<int ...data>
struct QuickSortWork<mvector<data...>> {
typedef m_diff<typename mvector<data...>::head_type, typename mvector<data...>::tail_type> diffed_type;
typedef typename QuickSortWork<typename diffed_type::right_type>::result_type right_type;
typedef typename QuickSortWork<typename diffed_type::left_type>::result_type left_type;
typedef typename combine_result<right_type, typename mvector<data...>::head_type, left_type>::result_type result_type;
};
template<>
struct QuickSortWork<mvector<>> {
typedef mvector<> result_type;
};
template<int ...data>
struct QuickSort {
typedef QuickSortWork<mvector<data...>> work_type;
constexpr static std::array<int, sizeof...(data)> result = work_type::result_type::value;
};```