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
有帮助吗?

解决方案

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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top