【问题标题】:Is there any way to strip a tuple of pairs to variadic template types or instantiat something with variadic types?有没有办法将一对元组剥离为可变参数模板类型或实例化可变参数类型的东西?
【发布时间】:2019-09-04 06:05:55
【问题描述】:

我有一个tuplepairs,其中每一对都有一个固定类型和一个变体类型。我想要的是一个变体类型列表或用这些类型定义一个对象(它肯定是用可变参数模板包构造的)。

根据How do I strip a tuple<> back into a variadic template list of types?,可以使用tuple 的组成类型来实例化某些东西。但是在这种情况下,我什至不知道它是否可能,如果可能的话,该怎么做。

想象一下我有这样的东西:

struct MyFixedType
{ /* ... */ };


using Tuple = std::tuple<
    std::pair<MyFixedType, int>,
    std::pair<MyFixedType, double>,
    std::pair<MyFixedType, std::string>
>;

我有这门课:

template <typename... Ts>
class MyClass
{
};

我想要的是用&lt;int, double, std::string&gt;声明一个MyClass的对象

注意:虽然这种情况可以使用预处理器或某些宏来处理,但我不能使用宏。

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    为了简洁,使用函数模板参数推导:

    template <class Fixed, class... Variant>
    MyClass<Variant...> MyClassFromPairTuple_impl(std::tuple<std::pair<Fixed, Variant>...> &&);
    
    template <class Tuple>
    using MyClassFromPairTuple = decltype(MyClassFromPairTuple_impl(std::declval<Tuple>()));
    

    用法:

    using Tuple = std::tuple<std::pair<MyFixedType, int>, std::pair<MyFixedType, double>, std::pair<MyFixedType, std::string>>;
    
    MyClassFromPairTuple<Tuple> instance; // MyClass<int, double, std::string>
    

    Live demo

    【讨论】:

      猜你喜欢
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多