How excpose and internal stl collection as read-only in my API?

I have a collection, as an example, based of type std::vector<MyClass>. How can I create a collection wrapper class that exposes only a count() property and an index operator?

I am struggling on how to make collection classes based on templates and/or inheritance. My library needs full access to the STL container for add and deleting elements. My library client should only see to a couple of read-only methods. My target is Linux.

Thanks in advance for any tips or suggestions,

-Ed
1
2
3
4
5
6
7
8
9
10
11
12
13

template<class T> //you can add the allocator template here too, if you need it.
class my_vector {
public:
    //put here all the functions you want to expose, directly calling vectors appropriate function
    //example:
    my_vector(unsigned n, const T& value = T()) : vec(n,value) {}
    T& operator[](unsigned i) { return vec[i]; } 
private:
    std::vector<T> vec;

};


This solution on a good complier makes no overhead.

You could solve the problem very similarly with private inheritance, I'm not sure which one is better, I would chose the one I made an example for.
Containment of an STL container is better than derivation since none of the containers
are equipped to be base classes (no virtual destructors).

However, the price for containment is you need to re-expose all of the methods of
the container you wish to contain.

eg, I would also expose begin() const, end() const, all the public typedefs from vector, etc, etc.

EDIT:

but what's better about this solution than simply passing a const std::vector<>& ?
Last edited on
Topic archived. No new replies allowed.