c++templatesstl

Detect if a container has iterator type or not


Consider the following pseudocode:

template<class Container>
int some_function(const Container& container)
{
      if (container has iterator) { // 
            // get an element by its iterator
      } else {
            // do another action
      }
}

So, we have a function template which takes a container type(e.g., vector, list, valarray or something else). Is it possible to determine (runtime) if a given container has iterator type? Compile time?


Solution

  • You use the detection idiom

    #include<experimental/type_traits>
    
    template<typename T>
    using iterator_t = typename T::iterator;
    
    template<typename T>
    constexpr bool has_iterator = std::experimental::is_detected_v<iterator_t, T>;
    
    template<class Container>
    int some_function(const Container& container)
    {
          if constexpr (has_iterator<Container>) {
                // get an element by its iterator
          } else {
                // do another action
          }
    }