如何编写一个以通用迭代器作为参数的模板函数
How can one write a templated function that takes a generic iterator as a parameter
我一直在编写静态模板class。对于其中一种方法,我希望能够传入任何迭代器,而不仅仅是来自特定数据结构(如 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;
}
以上是我尝试过的示例,但对于这种基本设计的不同变体,我不断收到各种编译器错误。
定义嵌套成员函数模板的正确方法是:
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;
}
我一直在编写静态模板class。对于其中一种方法,我希望能够传入任何迭代器,而不仅仅是来自特定数据结构(如 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;
}
以上是我尝试过的示例,但对于这种基本设计的不同变体,我不断收到各种编译器错误。
定义嵌套成员函数模板的正确方法是:
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;
}