I would like to write a type trait that, given a ContainerType, is capable to deduce the most nested IteratorType, meaning that given for example a std::vector<int> or a std::vector<std::vector<int>> or a std::vector<std::vector<std::vector<int>>> always the same IteratorType will be deduced, as if it is an std::vector<int>.
Here you go, I have written a trait and a tiny demonstration how it works:
#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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With