Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force key type of a std::map not to be const

Tags:

c++

map

stl

C++ references tells us for a std::map

typedef pair<const Key, T> value_type;

Is it possible to force the Key Type not to be const ? I need to do this in a template method like

template<class T> // T represent a map in general (std::map, boost::unordered_map or whatever..)
void foo(const T& m)
{
  typename T::value_type::first_type x;
  x=0; // Wrong because x is const ...
}
like image 333
Guillaume Thomas Avatar asked Jul 21 '11 09:07

Guillaume Thomas


2 Answers

No, it's not.

This is because map performs its internal ordering based on key. If you could modify the key yourself, willy-nilly, all hell would break loose.

You should use the provided API functions; where the use of one results in changing a Key value (actually I don't think that any do), the appropriate internal re-ordering may take place.

Think of getters and setters, and their use in providing an alternative to messy/dangerous direct member access.


However, you could write this:

template<class T>
void foo(const T& m)
{
   typename T::key_type x;
   x = 0;
}

std::map type aliases

key_type                Key
mapped_type             T
value_type              pair<const Key,T>
key_compare             Compare
value_compare           Nested class to compare elements
allocator_type          Allocator
reference               Allocator::reference
const_reference         Allocator::const_reference
iterator                Bidirectional iterator
const_iterator          Constant bidirectional iterator
size_type               Unsigned integral type (usually same as size_t)
difference_type         Signed integral type (usually same as ptrdiff_t)
pointer                 Allocator::pointer
const_pointer           Allocator::const_pointer
reverse_iterator        reverse_iterator<iterator>
const_reverse_iterator  reverse_iterator<const_iterator>
like image 58
Lightness Races in Orbit Avatar answered Sep 21 '22 14:09

Lightness Races in Orbit


typename T::key_type will give you the key type without adding a const qualifier.

like image 34
Mike Seymour Avatar answered Sep 21 '22 14:09

Mike Seymour