I have a template class that I am working on for a project that behaves a bit like one of the container classes in the C++ STL, but I am having some problems figuring out a good safe way to implement it.
Some background: I am trying to port an existing project called Artemis, an entity system framework, to C++ from Java. There is a class called bag that is essentially an ArrayList but the items it contains are stored in array and looked up with an index for faster access, the elements stored store their own index for the most part, but that is not really important.
The Problem: Okay, so I have a template class that contains an array of T (the template type). My issue is with returns of T elements. In my T &Get(int index) function, I want to return a reference to the element at the given index, but I do not know what to do if that element does not exist. I wanted to return something like null but that does not work since T‘s type is not guaranteed to be a pointer. I could have the container class contain T*s, but then I would hit some odd issues/complicate things for int and non-pointers (std::string) as well as some items going out of scope (unless I copied the value?).
Does anybody have any ideas or know how the built-in STL containers combat these issues?
I hope I made it clear enough what I am asking for…
Links:
- File I am porting
- My work so far (it is not beautiful so be warned)
File I am porting
Thank you in advance.
The standard associative containers (
map,unordered_map, etc) create a default-constructed object when the[]syntax is used and return a reference to that.You can either do that, or throw an exception when an element is not present. The standard associative containers have an
atfunction that does this.Another alternative is to have a function like the standard container’s
findfunction which returns an iterator to the element instead of a reference to an element. If the element is not present, the iterator returned is equal toend(container). This way you can actually check if the element is present without using exceptions.