如何将元函数应用于可变参数模板 class 的模板类型?

How to apply a meta function to the template types of a variadic template class?

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

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

我的客户 class 是一个可变参数模板,它可以使用 1 个或多个上述原子 classes:

template<class ...AtomicTypeArgPack>
class MyclassAcceptingAtomicTypes;

我有一个相关的通用 class 接受 Atomic*::inner_type 作为模板参数:

template<class ...InnerTypeArgPack>
class MyclassAcceptingInnerTypes;

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

using my_first_class_t = MyclassAcceptingAtomicTypes<Atomic1, Atomic2>;

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

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

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

试试这个:

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>);

Is there is way to automatically generate the second type (i.e. my_first_class_inner_types_t) from the first declaration (my_first_class_t) using template meta programming / meta functions?

你的意思如下?

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>{}, "!" );