问
在类的虚拟示例中
typedef myStruct<myStruct<myStruct<int>>> mv;
int
是最里面的模板参数。 如何获取任意嵌套深度的参数类型?
期望的结果
获取最内层类型的机制
innermost<mv>::type -> int
心愿单
这可以使用模板别名来完成吗(模板模板参数是这里缺少的功能)?
举个例子,我的类型是
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/