AntiClimacus AntiClimacus - 2 months ago 13
C++ Question

std::map::insert change in C++17

I see that the

insert
method of
std::map
and
std::unordered_map
is going to change from

template<class P> std::pair<iterator,bool> insert(P&& value); (C++11)


to

std::pair<iterator,bool> insert(value_type&& value); (C++17)


However, for these containers,
value_type
is
std::pair<A const, int>
. Two questions here:


  1. Why this change? What is the upside?

  2. How is this going to work to move a key on insertion? The C++11 version accepts anything (the constraint on
    P
    is
    default_constructible<value_type, P&&>
    ), then
    std::pair<A, int>
    - which is most of the time the type of this argument as it is the one returned by
    std::make_pair
    - and can call the move constructor of
    A
    . But in the C++17 version, this argument is casted to
    value_type
    , where
    A
    is const, then non-movable. A has to be copied, if I am not overlooking something. Or does C++17 change anything on that side too?



Thanks!

Answer

An additional non-template overload to insert was added in C++17.

Such an overload has the advantage that it permits .insert( { {key}, {value, args} } ) syntax -- {} based construction. template arguments cannot be passed {} based construction instructions without an explicit type.

Comments