gpt4 book ai didi

c++ - 如何在基类中实现子类迭代器的统一接口(interface)?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:20:52 24 4
gpt4 key购买 nike

在 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 *

最佳答案

你可以简单地使用模板类。查看我的示例,其中包含大小为 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
};

关于c++ - 如何在基类中实现子类迭代器的统一接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50444020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com