如何获取n嵌套向量的最内部类型

How to get the inner most type of a n-nested vector?

本文关键字:向量 嵌套 最内部 类型 何获取 获取      更新时间:2023-10-16

我需要得到一个n嵌套向量的内部类型。例如:

type a;                          //base_type of a = type
std::vector<type> b;             //base_type of b = type
std::vector<std::vector<type>> c;//base_type of c = type

等等。我尝试使用包装器,但这导致了编译器错误。

template<typename T1>
struct base_type : T1::value_type { };
template<typename T1>
struct base_type<std::vector<T1>> {
    using type = typename base_type<T1>::value_type;
};

您的两种情况都是错误的。

您的基本情况应该是非vector情况。对于非vector,不存在::value_type。你只需要类型:

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

对于递归情况,base_type的"结果"类型命名为type。不是value_type,所以我们必须在这里使用它:

template<typename T>
struct base_type<std::vector<T>> {
    using type = typename base_type<T>::type;
};

我们可以简化为:

template<typename T>
struct base_type<std::vector<T>> 
: base_type<T>
{ };