简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM