Re: hasMember
On 8 d=E9c, 11:03, Andrea Crotti <andrea.crott...@gmail.com> wrote:
Suppose I have a class like this
class Cont
{
private:
std::map<int, int> content;
bool hasMember(int idx);
int getValue(int idx);
};
Now what I'm doing now in cases like this is to make sure that every
time I call getValue I'm sure that the object is there, so I have to
call first hasMember.
In the caller I always do
if (obj.hasMember(idx))
int idx = obj.getValue(idx);
I assume you don't really want to use an uninitialized idx but want to
update idx value.
in this way I don't need to handle special cases when the thing is not
found, BUT in many cases this brings to useless computations, since
sometimes I have to scan the container twice.
Is there a better pattern in these situations which is not "return -1
if the object is not found"?
I don't know of pattern specifically.
Depending on your need, you can
* use something like Barton-Nackman's fallible<T> (this is the most
general solution):
// fallible<int> getValue(int idx);
fallible<int> idx = obj.getValue(n)
if( idx.isSet() ) ...
* use a default value (useful if you only want ot update a value),
maybe with an optional parameter telling you if the value is set or if
the default value was used:
// int getValue(int idx, int defaultValue, bool* isSet=0);
int idx = 42;
bool isSet;
idx = obj.getValue(idx,idx,&isSet);
if( isSet ) ...
* return a pointer (this is the most lightweight if you have an
adequate storage of the values to return).
// int const * getValue(int)
int const *idx = obj.getValue(n);
if( idx ) ...
There are other solutions but you would have to be more specific.
--
Michael