0
votes

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?

1
If it is an STL container then it has an iterator. But it is usually more flexible/reusable to take iterators as parameters rather than the container. - Galik
Do you need to support both the case where Container has an iterator type, and the case where it does not? Your code implies that you do, but that's not the question you asked. - tweej
Yes, I want to support both cases. My question is: determine if a container has iterator type or not and in the code snippet I expressed it as a condition. I think it is a question I asked. - David Hovsepyan
Galik, valarray is a container in terms of that it contains more than one element of the same type and it doesn't have iterator type. - David Hovsepyan

1 Answers

3
votes

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