Hi Heinz-Mario!
On Thursday, May 26, 2016 at 4:06:56 AM UTC-4, Heinz-Mario Frühbeis wrote:
> ...
> But now I have a further question...
> ...
> c_IDAMap <A*> mMap;
> Now adding e.g. "Hallo" and "Hi" (as Key!) ...
> And than calling:
> cout << mMap["Hallo"]; // Output is "Hallo"
>
> But calling...
> cout << mMap["Halo"];
> raises an error, which I currently cannot handle really good and the
> program crashes. The really problem is if the template is a pointer,
> because I'm not able to return NULL.
> Maybe because of 't_MapMember& operator [] (t_ItemGet vKey){' and the
> '&' after 't_MapMember'.
> It always returns a value other than NULL, so I cannot "ask" (if the
> template contains pointer)...
>
> if(mMap["Halo") == NULL) return; // E.g. ...
>
> Do someone have a suggestion how I can return NULL in case of a mismatch?
The general question you are asking is how to signal
that a key is not found when looking it up in a
collection, for example, in a key-value map.
Three approaches are common:
You can return a sentinel value -- a special value
not otherwise used that is deemed to mean "key not
found."
(In your specific case where you have a collection
of pointers, "c_IDAMap <A*> mMap;", if you know that
you will never store nullptr as a valid value in
your collection, then returning nullptr as the "key
not found" value could, indeed, work. If nullptr
could be a valid value, then this approach won't
work. Also, because you've made your collection
a class template whose stored type is not required
to be a pointer, you would need extra handling to
make your template code work sensibly for both pointer
and non-pointer types.)
You can return a default value. (See, for example,
how std::map::operator[] behaves when the key is not
found.)
You can throw an exception.
All of these work and can make sense depending on the
details of what you are trying to do. I would suggest
that you think about your use case, decide which of
these strategies makes the most sense for you, and then
drill down into the implementation details.