2

Assume I have a container type to which I would like to attach additional information. My approach would be to define a class holding the container and the info. Is it good practice to define methods for the new class which mimic the container's methods? E.g., instead of writing myContainerObject.internalVector[i] I would like to write myContainerObject[i]. One would have to redefine every method one wishes to use (size(), push_back() etc.). What are the drawbacks of such an approach? What alternatives exist (e.g., is inheriting from a container the better solution?).

4

3 回答 3

2

You are using composition with forwarding functions, and it's the right thing to do with concrete classes like STL containers. One drawback is that you have to redefine every overload of every function you want to allow, only to forward arguments, as well as parrot-typedef nested types (like iterator).

An alternative is to inherit but never publicly, only with private inheritance (because STL containers' destructor is public and non-virtual), then use using-declarations inside the custom class to bring names of base-class functions and types into scope (needing only one using Base::name; for all overloads of a function).

于 2013-07-24T08:10:19.820 回答
2

Possible ways of grasping a type which is a container, that I can think of:

  1. Provide the a decorator (this is what you are asking about) whose component will be the internal container. This is can work when you have strict interfaces which you must comply with. It's neither good or bad practice. Read about decorator design pattern.

  2. Use an iterator concept in your algorithms instead of a container. This a generic approach, and how stl algorithms are implemented

  3. Use a container concept - similar to (2). Detect if the type is a container (SFINAE trick) and manipulate it.

  4. Reimplement the container interface. You need a really strong reason to do it since it requires a significant amount of work/know-how. Some info: http://stdcxx.apache.org/doc/stdlibug/16-3.html

Generally , unless your uses case is very, very trivial or you have some specific requirements you should not expose class internal state (myContainerObject.internalVector[i]) to out side world.

于 2013-07-24T08:20:04.910 回答
0

Best practice is to keep the internals private and implement the [] operator and other functions (size() and such).

于 2013-07-24T08:00:11.500 回答