문제

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