如何推断嵌套最多的迭代器类型

How to deduce the most nested iterator type?

本文关键字:迭代器 类型 何推断 嵌套      更新时间:2023-10-16

我想写一个类型特征,给定一个ContainerType,能够推断出最嵌套的IteratorType,这意味着例如给定一个std::vector<int>std::vector<std::vector<int>>std::vector<std::vector<std::vector<int>>>总是会推导出相同的IteratorType,就好像它是一个std::vector<int>一样。

在这里,我写了一个特质和一个小小的演示,它是如何工作的:

#include <type_traits>
#include <iterator>
#include <vector>
template<class ...>
using void_t = void;    
template<class T, class = void>
struct is_container : std::false_type{};
template<class T>
struct is_container<T, void_t<decltype(std::begin(std::declval<T>())), decltype(std::end(std::declval<T>()))>> : std::true_type{};
template<class T, class = void>
struct drill_iterator {
    using type =  typename T::iterator;
};
template<class T>
struct drill_iterator<T, typename std::enable_if<is_container<typename T::value_type>::value>::type > {
    using type = typename drill_iterator<typename T::value_type>::type;
};

int main(){
    drill_iterator<std::vector<std::vector<int>>>::type a;
    drill_iterator<std::vector<int>>::type b;
    if(std::is_same<decltype(b), std::vector<int>::iterator>::value
    && std::is_same<decltype(a), std::vector<int>::iterator>::value)
        return 0;
    return 1;
}

在线演示