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
Was it helpful?

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top