lancegerday
lancegerday

Reputation: 762

How can one write a templated function that takes a generic iterator as a parameter

I've been writing a templated static class. For one of the methods, I want to be able to pass in any iterator not just one from a specific data structure like List.

template <class T> 
class Foo
{
public:
      template<typename InputIterator>
      static bool bar(T&, InputIterator start, InputIterator end);
};

template <class T, typename InputIterator>
bool Foo<T>::bar(T& data, InputIterator start, InputIterator end)
{
    typename InputIterator::const_iterator it = start;
    while(it != end)
    {
        //logic here
        it++;
    }
    return true;
}

Above is an example of what I've tried but I keep getting various compiler errors for different variations of this basic design.

Upvotes: 0

Views: 35

Answers (1)

cigien
cigien

Reputation: 60412

The correct way to define a nested member function template is:

template <class T>
template <typename InputIterator>
bool Foo<T>::inRange(T&, InputIterator start, InputIterator end)
{
    typename InputIterator::const_iterator it = start;
    while(it != end)
    {
        //logic here
        it++;
    }
    return true;
}

Upvotes: 3

Related Questions