繁体   English   中英

如何创建类型列表以扩展为元组?

[英]How do I create a type list to expand into a tuple?

我正在尝试创建一个具有传递给它的所有类型的元组的类。 我希望它将类型列表作为模板参数,并使用该列表中的类作为内部元组将包含的类。 目前,我有类似的东西,实际上并没有编译。

template<class ... T>
struct ComponentList {};

template<ComponentList<typename ...T> >
class ComponentManager{
    std::tuple<T...> components;
};

我想让ComponentList成为自己的类型的原因是因为我想稍后传入其他类型列表。 这可能吗? 如果没有,那会有什么替代方案呢?

您可以添加模板以将类型级别列表中的参数重新绑定到std::tuple

template<class A, template<class...> class B>
struct rebind_;

template<template<class...> class A, class... T, template<class...> class B>
struct rebind_<A<T...>, B> {
    using type = B<T...>;
};

template<class A, template<class...> class B>
using rebind = typename rebind_<A, B>::type;

然后像这样使用它:

template<class... T>
struct ComponentList {};

template<class List>
struct ComponentManager {
    rebind<List, std::tuple> components;
};

int main() {
    using List = ComponentList<int, char, long>;
    ComponentManager<List> manager;
    std::cout << std::get<0>(manager.components) << '\n';
}

我想如果你想强制原始类型是ComponentList ,你可以使用enable_ifis_instantiation_of

template<class List,
    typename = std::enable_if<is_instantiation_of<List, ComponentList>::value>::type>
struct ComponentManager {
    rebind<List, std::tuple> components;
};

您是否能够强制所有类型列表类提供带有内部类型的tuple_t类型? 就像是:

template <class ... T>
struct ComponentList {
    typedef std::tuple<T...> tuple_t;
};

template<class T>
class ComponentManager {
    typename T::tuple_t components;
};

用法是你所期望的:

ComponentManager<ComponentList<int, double> > cm;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM