Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract wrapper for stl containers?

I'd want to expose some objects as abstract containers with stl-style manipulation possibilities (for_each loops, iterators) and hide container implementation details.

Performance issues don't matter (virtual calls and even memory allocation while copying "universal" iterator is acceptable).

I'm going to write an abstract container interface with pure virtual functions (+ "universal" iterator over the container) and an implementaition adapter for stl sequential containers.

But maybe there are useful existing libraries for this purpose?

Or it's totally a bad idea?

like image 577
user396672 Avatar asked Mar 16 '11 17:03

user396672


2 Answers

Thomas Becker has some useful advice (type erasure). You may also find Stroustrup's SCARY paper useful.

like image 160
Max Lybbert Avatar answered Sep 23 '22 07:09

Max Lybbert


If your "objects" aren't STL objects but custom ones, I think it's a good idea.

As you can see on http://www.sgi.com/tech/stl/Vector.html , vector "is a model of" RandomAccessContainer. Most Boost packages use similar concepts (the term realy is "concept")

In C++, you've got two possibilities to do this :

  • An abstract class (interface) as you suggested
  • Templates

With templates you can do something as :

doSomething < AnythingThatIsIterable >(AnythingThatIsIterable i){
    for (AnythingThatIsIterable::itertaor it = i.begin(); it != i.end(); ++i){
        it->foo()
    }
}
  • Any class which provides an iterator, begin and end will work : std::vector, but also your own objects.
  • These objects don't have to inherit from any interface, so std::vector will work.
like image 41
Calvin1602 Avatar answered Sep 22 '22 07:09

Calvin1602