【问题标题】:How to implement a unified interface of child classes's iterators in base class?如何在基类中实现子类迭代器的统一接口?
【发布时间】:2018-10-30 19:48:30
【问题描述】:

在 C++ 中,假设我有一个基类 Base,许多子类都派生自它。每个子类都包含一个具有某种类型和长度的数组。

class Base {
    //...
    int baseData;
    virtual ChildIterator getBegin();
    virtual ChildIterator getEnd();
};
class Child1 : public Base {
    // ...
    static const size_t CAPACITY = 5;
    int ints[CAPACITY];
    ChildIterator getBegin() { return &ints[0]; }
    ChildIterator getEnd() { return &ints[CAPACITY]; };
};
class Child2 : public Base {
    // ...
    static const size_t CAPACITY = 7;
    float floats[CAPACITY];
    ChildIterator getBegin() { return &floats[0]; }
    ChildIterator getEnd() { return &floats[CAPACITY]; };
};

现在,我想让每个子类都可以迭代,也就是说,我可以遍历每个子对象的数组成员,如下所示:

Base *p1 = new Child1(...);
Base *p2 = new Child2(...);

sort(p1->getBegin(), p1->getEnd());
// same as: sort(&((Child1)p1->ints[0]), &((Child1)p1->ints[5]));

sort(p2->getBegin(), p2->getBegin() + 3);
// same as: sort(&((Child2)p2->floats[0]), &((Child2)p2->floats[3]));



// Please note that sort() is not my intended operation on them;
// I just use it as an example because it involves iterators. I know
// I could just define sort() method in each child class.

我应该如何实现ChildIterator 类,使其成为有效的随机访问迭代器?

编辑

数组中的类型不只是intfloat;可能是Base *Child *,如果数组中的类型是Base *,我需要通过ChildIterator访问Base的成员。

【问题讨论】:

  • @Jarod42 不 - 类型可以是任何类型,甚至是 Base *
  • 那么这是不可能的(一般来说)。 *ChildIterator{} 应该是什么类型?
  • @PasserBy: 具有某种std::any 的代理类型?
  • 我希望有一些聪明的技巧可以解决..
  • @Swift 它是循环的而不是递归的;)

标签: c++ iterator polymorphism


【解决方案1】:

您可以简单地使用模板类。请看我的示例,其中包含大小为 5 的整数数组的类。

class Base
{
   // Dummy
};

template<typename TArray, int size>
class Container : public Base
{
public:
    TArray* getBegin()
    {
       return elements;
    }

    TArray* getEnd()
    {
       return elements + size;
    }

private:
    TArray elements[size];
};

class Child : public Container<int, 5>
{
    // Some Child class specific implementation
};

【讨论】:

  • 谢谢!但如果我希望元素类型为Base *,则它不起作用。
  • 嗯..我不得不承认这很聪明!让我考虑一两天,看看它是否可以处理其他一些极端情况:)
  • 我只是看到这可能不符合您的需要,因为无法从 Base* 访问迭代器,并且需要进行一些转换。
  • 哦,你的意思是我需要从迭代器访问 Base * 吗?确实你是对的。让我把这个添加到问题中。
  • 恐怕你无法满足这个问题的所有要求。请看这个问题的答案stackoverflow.com/questions/16240799/…
猜你喜欢
  • 1970-01-01
  • 2012-05-24
  • 1970-01-01
  • 2016-07-22
  • 2022-01-10
  • 2018-03-07
  • 2021-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多