【问题标题】:How do I create a type list to expand into a tuple?如何创建类型列表以扩展为元组?
【发布时间】:2016-02-04 01:34:54
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c++ c++11 c++14


    【解决方案1】:

    您可以添加模板以将类型级别列表中的参数重新绑定到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;
    };
    

    【讨论】:

      【解决方案2】:

      您能否强制要求所有类型列表类都提供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;
      

      【讨论】:

      • 这是一种可能性,但我希望有一个更好的解决方案,既可以将提供的类的类型强制为ComponentList,也可以操作类型列表中的类型(例如,不是将它们制作成元组,而是将每种类型都设为该类型的向量并将其粘贴在元组中)。
      猜你喜欢
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多