Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator overloading for C++ maps

Tags:

c++

templates

I need help understanding some C++ operator overload statements. The class is declared like this:

template <class key_t, class ipdc_t>
class ipdc_map_template_t : public ipdc_lockable_t
{
    ...
    typedef map<key_t,
            ipdc_t*,
            less<key_t>> map_t;
    ...

The creator of the class has created an iterator for the internal map structure:

struct iterator : public map_t::iterator
{
    iterator() {}
    iterator(const map_t::iterator & it)
        : map_t::iterator(it) {}
    iterator(const iterator & it)
        : map_t::iterator(
            *static_cast<const map_t::iterator *>(&it)) {}
    operator key_t() {return ((this->operator*()).first);}           // I don't understand this.
    operator ipdc_t*() const {return ((this->operator*()).second);}  // or this.

};

And begin() and end() return the begin() and end() of the map:

iterator begin() {IT_ASSERT(is_owner()); return map.begin();}
iterator end() {return map.end();}

My question is, if I have an iterator, how do I use those overloads to get the key and the value?

ipdc_map_template_t::iterator iter;
    for( iter = my_instance.begin();
             iter != my_instance.end();
         ++iter )
    {
        key_t my_key = ??????;
        ipdc_t *my_value = ??????;

    }
like image 546
indiv Avatar asked Aug 14 '26 09:08

indiv


1 Answers

These are typecast operators, so you can do this:

{
    key_t   key = iter;
    ipdc_t *val = iter;
}

Or, since ipdc_map_template::iterator is a subclass of std::map::iterator, you can still use the original accessors (which I find more readable):

{
    key_t   key = (*iter).first;
    ipdc_t *val = (*iter).second;

    // or, equivalently
    key_t   key = iter->first;
    ipdc_t *val = iter->second;

}
like image 141
joeld Avatar answered Aug 16 '26 23:08

joeld



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!