在类
的虚拟示例中typedef myStruct<myStruct<myStruct<int>>> mv;
int
是最里面的模板参数。 如何获取任意嵌套深度的参数类型?
获取最里面类型的机制
innermost<mv>::type -> int
可以使用模板别名来完成(模板模板参数在这里是缺少的功能)吗?
在我的类型为
的示例中vector<vector<vector<int>>>
考虑到vector
需要额外的模板参数,有没有办法执行相同的操作?当然,可以划分一个独特的实现,但是有没有办法扩展第一个问题的解决方案来处理这些情况呢?
答案 0 :(得分: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()
{
}
答案 1 :(得分:7)
在0x499602D2's answer的基础上,我们得到以下内容,只考虑第一个模板参数(如果有的话)。是的compiles。它也稍微简单一些。
#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()
{
}
请注意,不会尝试验证反复使用相同的模板。