gpt4 book ai didi

c++ - 根据非类型参数值推导出类型列表

转载 作者:行者123 更新时间:2023-12-01 14:04:37 25 4
gpt4 key购买 nike

我有一个类,可以在可变参数模板参数中使用未定义数量的策略进行自定义:

template<typename... Features>
class A : public Features... {};

所述功能通过 constexpr uint8_t 的位启用, 如:
0x1 --> X1 enabled
0x2 --> X2 enabled
0x3 --> X1, X2 enabled
0x4 --> X3 enabled
0x5 --> X1, X3 enabled
etc...

我如何编写辅助类型来推断正确的类型列表并将其转发到 class A的可变参数模板参数?

使用 std::conditional我可以写出这样的东西,但正如你想象的那样,它很快就会变得可怕。

using ExtendedA = A<MandatoryFeature, std::conditional_t<HasX1(), X1, std::monostate>;

或者使用我可以编写的帮助器类型和模板特化

template<uint8_t value>
struct Features {};

template<>
struct Features<0x3> {
using type = std::tuple<X1, X2>;
};

但是我需要打开包装 Features<0x3>::typeclass A的例子,我不知道我应该怎么写。

最佳答案

要将您的标志转换为功能的集合(元组),您可以使用类似于以下内容的代码:

template <std::size_t> struct Feature;

template <> struct Feature<0> { using type = X0; };
template <> struct Feature<1> { using type = X1; };
template <> struct Feature<2> { using type = X2; };
template <> struct Feature<3> { using type = X3; };
template <> struct Feature<4> { using type = X4; };
template <> struct Feature<5> { using type = X5; };
// ...
constexpr std::size_t FeaturesCount = /*..*/;

template <std::size_t Flag, std::size_t...Is>
auto CollectFeaturesImpl(std::index_sequence<Is...>)
-> decltype(std::tuple_cat(
std::conditional_t<
(Flag & (1U << Is)) != 0,
std::tuple<typename Feature<Is>::type>,
std::tuple<>>
{}...
))

template <std::size_t Flag>
using CollectFeatures_t =
decltype(CollectFeaturesImpl<Flag>(std::make_index_sequence<FeaturesCount>()));

But then I would need to unpack Features<0x3>::type for class A's instance, and I'm not sure how I should write that.



使用额外的层,您可以“解包”元组:
template<typename Tuple> struct AFromTuple;

template<typename... Features>
struct AFromTuple<std::tuple<Features...>>
{
using type = A<Features...>;
};

using myA = AFromTuple<std::tuple<X1, X3>>::type; // A<X1, X3>

或者
template<typename Tuple> struct FromTuple;

template<typename... Features>
struct FromTuple<std::tuple<Features...>>
{
template <template <typename...> Class C>
using map = C<Features...>;
};

using myA = FromTuple<std::tuple<X1, X3>>::map<A>; // A<X1, X3>

关于c++ - 根据非类型参数值推导出类型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61008369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com