如何获取最里面的模板参数类型?

Nik*_*iou 5 c++ templates template-meta-programming c++11

Q

在一个类的虚拟示例中

typedef myStruct<myStruct<myStruct<int>>> mv;
Run Code Online (Sandbox Code Playgroud)

int是最里面的模板参数.如何获取任意嵌套深度的参数类型?

期望的结果

获取最内层类型的机制

innermost<mv>::type -> int
Run Code Online (Sandbox Code Playgroud)

愿望清单

  1. 可以使用模板别名来完成(模板模板参数在这里是缺少的功能)吗?

  2. 在我的类型将是一个例子中

    vector<vector<vector<int>>>
    
    Run Code Online (Sandbox Code Playgroud)

    有没有办法执行相同的操作,因为vector需要额外的模板参数?当然,可以划分一个独特的实现,但是有没有办法扩展第一个问题的解决方案来处理这些情况呢?

0x4*_*2D2 7

请尝试以下方法.如果模板有多个元素,它也会返回一个元组:

#include <tuple>
#include <type_traits>

template<typename T>
struct innermost_impl
{
    using type = T;
};

template<template<typename> class E, typename T>
struct innermost_impl<E<T>>
{
    using type = typename innermost_impl<T>::type;
};

template<template<typename...> class E, typename... Ts>
struct innermost_impl<E<Ts...>>
{
    using type = std::tuple<typename innermost_impl<Ts>::type...>;
};

template<typename T>
using innermost = typename innermost_impl<T>::type;

template<class>
struct X;

static_assert(std::is_same<innermost<X<X<X<int>>>>, int>::value, "");

int main()
{
}
Run Code Online (Sandbox Code Playgroud)


Mat*_* M. 7

0x499602D2的答案的基础上,我们得到以下内容,只考虑第一个模板参数,如果有的话.是的,它编译.它也稍微简单一些.

#include <tuple>
#include <type_traits>
#include <vector>

template<typename T>
struct innermost_impl
{
    using type = T;
};

template<template<typename...> class E, typename Head, typename... Tail>
struct innermost_impl<E<Head, Tail...>>
{
    using type = typename innermost_impl<Head>::type;
};

template<typename T>
using innermost = typename innermost_impl<T>::type;

template<class>
struct X;

static_assert(std::is_same<innermost<X<X<X<int>>>>, int>::value, "");

static_assert(
    std::is_same<innermost<std::vector<X<std::vector<int>>>>, int>::value,
    ""
);

int main()
{
}
Run Code Online (Sandbox Code Playgroud)

请注意,不会尝试验证反复使用相同的模板.