C++ 模板参数排序

问题描述 投票:0回答:1

我正在寻找模板代码来按模板参数的静态成员函数的返回值对模板参数进行排序

static constexpr int getType()
,例如:

#include <iostream>
#include <type_traits>

struct A {
    static constexpr int getType() { return 1; }
};

struct B {
    static constexpr int getType() { return 2; }
};

struct C {
    static constexpr int getType() { return 3; }
};

template <typename...T>
struct Sort { /*...*/ };

int main() {
    using Sorted = Sort<C, A, B>::type; // std::tuple<A, B, C> or something like
    std::cout << typeid(Sorted).name() << std::endl;
    return 0;
}

无论如何,我想要一个以任何形式升序排列的类型名称序列。

c++ templates template-meta-programming compile-time
1个回答
0
投票

使用Boost.Mp11你可以

#include <boost/mp11.hpp>

using namespace boost::mp11;

template<class LHS, class RHS>
struct Less : std::bool_constant<LHS::getType() < RHS::getType()> {};

template <typename... Ts>
struct Sort {
  using type = mp_sort<mp_list<Ts...>, Less>;
};

生成一个

mp_list
,其中类型已排序。

演示

© www.soinside.com 2019 - 2024. All rights reserved.