So is this just missing from those libraries or is converting to a
std::map
not really intended to be allowed?
std::map to std::vector:
According to the description of [range.utility.conv.to], this
map<int, double> m;
auto f = ranges::to<vector>(m);
will invoke the following overload
template<template<class...> class C, input_range R, class... Args>
constexpr auto to(R&& r, Args&&... args);
Let DEDUCE_EXPR
be defined as follows:
C(declval<R>(), declval<Args>()...)
if that is a valid expression,
- otherwise,
C(from_range, declval<R>(), declval<Args>()...)
if that is a valid expression,
- otherwise,
C(declval<input-iterator>(), declval<input-iterator>(), declval<Args>()...)
if that is a valid expression,
- otherwise, the program is ill-formed.
Returns: to<decltype(DEDUCE_EXPR)>(std::forward<R>(r), std::forward<Args>(args)...)
.
Where C
is vector
, R
is map<int, double>&
, and Args...
is empty parameter pack. Note that C++23 introduces the following range version constructor for vector
template<container-compatible-range<T> R>
constexpr vector(from_range_t, R&& rg, const Allocator& = Allocator());
Effects: Constructs a vector object with the elements of the range rg
,
using the specified allocator.
and the following CTAD
template<ranges::input_range R, class Allocator = allocator<ranges::range_value_t<R>>>
vector(from_range_t, R&&, Allocator = Allocator())
-> vector<ranges::range_value_t<R>, Allocator>;
So C(from_range, declval<R>())
is a valid expression, and the type of DEDUCE_EXPR
will be vector<pair<const int, double>>
, which will further invoke
to<vector<pair<const int, double>>>(m);
which will construct a vector
with value_type
of pair<const int, double>
through the range version constructor.
So ranges::to<vector>(m)
in C++23 is basically equivalent to
map<int, double> m;
vector f(m.begin(), m.end());
The reason range-v3 fails is that its internal implementation detects that vector<pair<const int, double>>
is reservable, so it will first default construct the vector
and call v.reserve()
to pre-allocate the memory, and then copy the map
by calling v.assign()
, but since pair<const int, double>
is not copy assignable, so compilation fails.
I suspect this is an implementation bug of range-v3, since it would compile if the vector
's reserve()
function didn't exist, and this optimized overload doesn't seem to constrain that the value_type
must be copy-assignable.
std::vector to std::map:
And for the following
auto g = ranges::to<map>(f);
Since std::map
also has the following constructors and corresponding CATD in in C++23
template<container-compatible-range<value_type> R>
map(from_range_t, R&& rg, const Compare& comp = Compare(), const Allocator& = Allocator());
So following the same rules of the game, we will get a map<int, double>
.