Question

#include <QMultiMap>

template <typename TKey, typename TValue>
TKey lastKeyOf(const QMap<TKey, TValue>& map)
{
    if (map.isEmpty())
        throw something;
    return (map.end() - 1).key();
}

The reason I ask is that:

template <typename TKey, typename TValue>
QMultiMap<TKey, TValue>;

inherits QMap<TKey, TValue> publicly. So if I call:

QMultiMap<int, std::string> multimap;
...
lastKeyOf(multimap);

All the calls inside lastKeyOf get statically bound to their QMap versions instead of QMultiMap versions, since QMap was not intended for polymorphic use (no virtual destructor).

I am not even sure what is this use called. Is it object slicing?

Was it helpful?

Solution

I believe this should be safe. QMultiMap just adds a new set of overloaded methods to QMap, you'll only get unexpected results if you use a function inside lastKeyOf() which is overloaded in QMultiMap to have different behavior. The only overloaded method with a compatible signature and different behavior that I can see is insert().

Having said that, it may make for more straightforward code to avoid QMultiMap and use QMap only with QMap::insertMulti() instead of QMap::insert().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top