c++ - Providing access to collection of abstract classes -
i designing interface (an abstract class) in c++ implements kind of tree structure: each instance has zero, one, or more children. children instances of interface.
i put quite thought interface not exclude particular implementations. example, methods should not return references forces implementation store value somewhere. exclude implementations recalculate value on each call; or wrappers transform returned value in way.
however, interface, unsure best way provide access children of instance. far, i've come 2 options:
class interface { public: virtual ~interface() = default; // idea 1: return collection of references. virtual auto getchildren() const -> std::vector<std::reference_wrapper<interface>> = 0; // idea 2: accept visitor. virtual void visitchildren(const std::function<void(interface&)> &visitor) const = 0; };
my question: best* way provide access collection of abstract classes. other ideas , approaches appreciated (e.g. iterator-based approach, if @ possible).
*any or of following properties: idiomatic, flexible, scalable, maintainable, intuitive, semantically strongest, ...
placing discussion of design being java-like aside. if want close idiomatic c++, go iterators:
class interface { class iterator_impl { virtual ~iterator_impl() = default; // fill rest }; public: class iterator { std::unique_ptr<iterator_impl> _impl; iterator(std::unique_ptr<iterator_impl> impl) : _impl(std::move(impl)) {} public: iterface& operator*() { //forward _impl } }; virtual iterator begin() = 0; virtual iterator end() = 0; };
after supplying complete iterator protocol, interface&
can used in idiomatic c++ code:
void foo(interface& interface) { for(auto& : interface) { //do stuff } }
Comments
Post a Comment