Question

Suppose a class like

class Foo
    {
    private:
        ANonTrivialContainer bar;
        OtherData baz;
    };

The iterators of ANonTrivialContainer are bi-directional. From outside, I want to do stuff with the contents of bar. What is prefferable of

  • Providing a beginBar() and a corresponding endBar(), returning iterators for ANonTrivialContainer like the accepted answer of Allowing access to container objects in C++. This will work, but exposes internal details to the caller (since it needs to do explicit calls to the underlaying class).
  • Providing a custom iterator that forwards all calls to an internal iterator. beginBar and endBar now returns the custom iterator instead.
  • Providing a forEach method that takes a reference to an object of a Callback class
Était-ce utile?

La solution

I would provide a visitBars generic method, taking a functor as the parameter.

template<typename F> void visitBars(F visit) {
  for(auto b: bar)
    visit(b);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top