Search code examples
c++templatesstliterator

How to make sure an iterator template parameter has the same data type as the template parameter of a template class


Sorry for the long title... Please let me know how to make it better...

I have a template class:

template <typename T>
class Example {
    ...
    template <typename Iterator>
    void add(const Iterator begin, const Iterator end);
    ...
};

How do I ensure the data type pointed by Iterator is T?

Another related question:

How does this STL vector constructor

template <class InputIterator>
vector (InputIterator first, InputIterator last, 
    const allocator_type& alloc = allocator_type());

make sure the InputIterator has a compatible data type as the vector?

Edit:

Is there a compile time solution?


Solution

  • You can do the following:

    template <typename Iterator>
    void add(const Iterator begin, const Iterator end)
    {
       static_assert(std::is_same<typename std::iterator_traits<Iterator>::value_type,
                     T>::value, "Iterator must be the same as T");
    }