【问题标题】:How can one write a templated function that takes a generic iterator as a parameter如何编写一个将泛型迭代器作为参数的模板化函数
【发布时间】:2020-09-28 04:28:51
【问题描述】:

我一直在编写一个模板化的静态类。对于其中一种方法,我希望能够传入任何迭代器,而不仅仅是来自特定数据结构(如 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;
}

以上是我尝试过的一个示例,但对于这个基本设计的不同变体,我不断收到各种编译器错误。

【问题讨论】:

  • 什么编译器错误?将其添加到问题中。
  • 什么是&amp;T?应该是T&amp;
  • 抱歉,当我问这个问题(工作问题,我在家问)时,我面前没有我的源代码,所以我的例子有一些问题。跨度>

标签: c++ templates iterator c++98


【解决方案1】:

定义嵌套成员函数模板的正确方法是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    相关资源
    最近更新 更多