C++ STL Wrapper – How to Design an Effective Wrapper

cdesignstl

Where I work we have our own system library, which pretty much is only wrappers around the STL, such as:

template <typename T>
class HVector {
protected:
    std::vector<T> data;
public:
    int size () const; //Only returns data.size()
    int custom(); //Some generic custom function that uses the data vector
}

Most of the class members are just re-declarations of the STL container members, but we also have a few customized functions that do some generic tasks with the container.

Is this a good design? If not, what would be the best way to implement the customized functions around the containers?

Best Answer

It depends on the nature of those custom operations, but probably yes, it's bad design. And the main reason for stating this is that you are coupling operation and storage.

If a certain custom operation is semantically independent, it can be better implemented as an standalone (functor) class or function, taking an specific container parameter. Moreover, if it doesn't depend on the concrete container class, it can be added an extra template parameter specifying it, or even better, refactored in order to work over iterator ranges. See, just like the STL algorithm functions.

Also, wrapping the way you do it involves forwarding a significant part of the wrapped container's public interface. This is a clear smell.

Related Topic