【问题标题】:How to deduce the most nested iterator type?如何推导出嵌套最多的迭代器类型?
【发布时间】:2019-06-12 16:07:16
【问题描述】:

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

【问题讨论】:

  • 你用的是哪个c++版本?
  • 我正在使用 C++11 和 GCC

标签: c++ c++11 iterator containers typetraits


【解决方案1】:

给你,我已经写了一个特征和一个小演示它是如何工作的:

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

Online demo

【讨论】:

  • 虚拟 +2 的真棒命名。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
相关资源
最近更新 更多