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

标签 c++ templates c++11 template-meta-programming

在类的虚拟示例中

typedef myStruct<myStruct<myStruct<int>>> mv;

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

期望的结果

获取最内层类型的机制

innermost<mv>::type -> int

心愿单

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

  2. 举个例子,我的类型是

    vector<vector<vector<int>>>
    

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

最佳答案

尝试以下操作。如果模板有多个元素,它也会返回一个元组:

#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()
{
}

关于c++ - 如何获取最里面的模板参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25187323/

相关文章:

c++ - 如何将小部件(例如 QPushButton)动态添加到设计器内置的布局

c++ - boost program_option 不区分大小写的解析

c++ - 专门用于枚举的模板

c++ - 我可以在模板参数中声明一个 constexpr lambda 吗?

c++ - boost::regex 和 std::regex 之间的不一致

c++ - 打印 unique_ptr 到 cout

c++ - Qt:优化绘画事件

c++ - 使用模板元编程来包装 C 风格的可变参数

ruby-on-rails - 将 AdminLTE 集成到 Ruby on Rails

c++ - 使用 unique_ptr 控制文件描述符