Boost logo

Boost :

From: Fernando Cacciola (fernando_cacciola_at_[hidden])
Date: 2005-01-13 18:44:26


"Ulrich Eckhardt" <uli_at_[hidden]> escribió en el mensaje
news:200412301330.34012.uli_at_doommachine.dyndns.org...
>I had the idea to use boost::optional on the interface of a std::map-like
> object. I have neither coded a prototype nor is this a fully grown design
> yet, I'd just like to discuss this idea.
>

Sorry for the late respond... I had to finish a product by yesterday.

> The rough outline is this:
>
> class my_map
> {
> public:
> optional<value>& operator[](key const&);
> optional<value> const& operator[](key const&) const;
> // iterators, ctors, dtor, etc the same
> private:
> optional<value> const m_empty_value;
> tree< pair<key, optional<value> > > m_content;
> };
>
>
> The important differences to std::map are:
> 1. operator[] is available as const and non-const memberfunction. The
> const
> memberfunction returns 'm_empty_value' in case the key is not found. The
> non-const one inserts a new node into the tree and returns a reference to
> that.
> 2. operator[] return an optional<value>, not a direct value. This means
> that
> you have to check the return-value of this call. OTOH, you _can_ check the
> return value to see if a key was associated with a value.
>

I think most people would object that the non-const version never returns an
uninitialized object, so the the optional<> wrapper is not really needed at
all.

OTOH, the current std::map operator[] signature is very appropiate, but the
non-const version is bound to be missing because otherwise we would have two
versions of the same operator with different signatures... very very bad.

Your proposal allows us to have non-const operator[], which I think is very
very usefull when working with associative containers.

So I like it :-)

Notice that optional<> supports direct assignment, so you can write

mymap[key]=value

directly, just like with std::map..

you dont need mymap[key].reset(value)

Also, you don't need to change anything else from std::map, so iterators can
remain the same..
That is, the following example that you wrote won't be applicable:

> ///////// iterating and accessing
> for(std::map<string,float>::const_iterator it=stdmap.begin();
> it!=stdmap.end();
> ++it)
> access(it->second);
>
> for(my_map<string,float>::const_iterator it=mymap.begin();
> it!=mymap.end();
> ++it)
> if(it->second)
> access(*(it->second));
>

Best,

Fernando Cacciola
SciSoft


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk