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

筅森魡賤 提交于 2019-12-02 08:30:26

问题


I need to get the inner type of a n-nested vector. For Example:

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

and so on. I tried using a wrapper, but this results in a compiler error.

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;
};

回答1:


Both of your cases are wrong.

Your base case should be the non-vector case. For a non-vector, there is no ::value_type. You just want the type:

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

For your recursive case, base_type's "result" type is named type. Not value_type, so we have to use that here:

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

which we can simplify to just:

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


来源:https://stackoverflow.com/questions/30960715/how-to-get-the-inner-most-type-of-a-n-nested-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!