Richard
Richard

Reputation: 15592

Is it allowed to cast unordered_map to map?

As title says, is it allowed? If not, are they sharing the same interface or abstract class anyway? I did not find any reference from online documents. but looks unordered_map and map are using the same functions.

Upvotes: 2

Views: 6500

Answers (4)

anio
anio

Reputation: 9171

You can reinterpret cast one thing to any other thing, even if it makes no sense. The compiler won't stop you if you force it, which is essentially what reinterpret cast is. Casting map to unordered_map makes no sense & won't work.

Why do you want to cast map to unordered_map? They have the same interface. You gain nothing by casting it.

Upvotes: 0

bdonlan
bdonlan

Reputation: 231443

STL classes do not use virtual functions; there is no consistent base class you can cast through (ie, there's no equivalent to Java's java.util.Map). You can't cast between std::unordered_map and std::map any more than you could cast between HashMap and TreeMap in java - they're completely different types and cannot be used equivalently.

If you want a function to be able to take multiple types of STL containers, just use a template function:

template<typename Map>
void somefunc(Map &mymap) {
  // ...
}

Upvotes: 1

Cat Plus Plus
Cat Plus Plus

Reputation: 129984

They're two unrelated types. If you want to construct one based on the other, you need to use constructors that take iterator range (C++11):

template <class InputIterator>
map(InputIterator first, InputIterator last,
    const Compare& comp = Compare(), const Allocator& = Allocator());

template <class InputIterator>
unordered_map(InputIterator f, InputIterator l,
              size_type n = see below,
              const hasher& hf = hasher(),
              const key_equal& eql = key_equal(),
              const allocator_type& a = allocator_type());

Upvotes: 7

Useless
Useless

Reputation: 67822

No, they're totally different and even if you force it with reinterpret_cast, it'll just go horribly wrong at runtime (ie, the dreaded Undefined Behaviour).

They're both STL containers, so deliberately have consistent interfaces. That doesn't mean they're the same thing internally.

Upvotes: 13

Related Questions