【问题标题】:How to apply a meta function to the template types of a variadic template class?如何将元函数应用于Variadic模板类的模板类型?
【发布时间】:2023-03-06 07:45:02
【问题描述】:

假设我有许多原子结构,每个都有一个inner_type

struct Atomic1{
    using inner_type = int;
};
struct Atomic2{
    using inner_type = double;
};
struct Atomic3{
    using inner_type = bool;
};
...

我的客户端类是一个可变参数模板,可以使用上述原子类中的一个或多个:

template<class ...AtomicTypeArgPack>
class MyclassAcceptingAtomicTypes;

我有一个相关的泛型类,它接受Atomic*::inner_type 作为模板参数:

template<class ...InnerTypeArgPack>
class MyclassAcceptingInnerTypes;

我的特定 api 类已定义,但指定了几个模板类型:

using my_first_class_t = MyclassAcceptingAtomicTypes<Atomic1, Atomic2>;

对于每个特定的类,我还有另一类内部类型:

using my_first_class_inner_types_t = MyclassAcceptingInnerTypes<Atomic1::inner_type ,  Atomic2::inner_type >;

有没有办法使用模板元编程/元函数从第一个声明(my_first_class_t)自动生成第二种类型(即my_first_class_inner_types_t)?

【问题讨论】:

    标签: c++ c++11 variadic-templates template-meta-programming typetraits


    【解决方案1】:

    试试这个:

    template <class Atomics>
    struct inner_types;
    
    template <template <class...> class T, class... Atomic>
    struct inner_types<T<Atomic...>>
    {
        using type = MyclassAcceptingInnerTypes<typename Atomic::inner_type...>;
    };
    
    
    using atomics = MyclassAcceptingAtomicTypes<Atomic1, Atomic2>;
    using inners  = MyclassAcceptingInnerTypes<Atomic1::inner_type ,  Atomic2::inner_type >;
    
    static_assert(std::is_same_v<inner_types<atomics>::type, inners>);
    

    【讨论】:

      【解决方案2】:

      有没有办法使用模板元编程/元函数从第一个声明(my_first_class_t)自动生成第二种类型(即my_first_class_inner_types_t)?

      你的意思是以下吗?

      template <typename ... Ts>
      constexpr auto foo (MyclassAcceptingAtomicTypes<Ts...> const &)
         -> MyclassAcceptingInnerTypes<typename Ts::inner_type...>;
      
      template <typename T>
      using bar = decltype(foo(std::declval<T>()));
      

      你可以验证

      static_assert( std::is_same<bar<my_first_class_t>,
                                  my_first_class_inner_types_t>{}, "!" );
      

      【讨论】:

        猜你喜欢
        • 2015-03-08
        • 2013-08-19
        • 1970-01-01
        • 2010-12-19
        • 2019-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多