The following code
using vptr = std::vector<std::unique_ptr<int>>;
auto m = std::unordered_map<int, std::any>{};
m.try_emplace(0, move(vptr{}));
Fails to compile, complaining about using of deleted copy constructor of unique_ptr
. After replacing std::any
with vptr
in template argument this code compiles, so the issue is clearly with any
How can I force std::any
to be moved instead of copied?
The problem is not moving std::any
, it's that std::any
itself does not support move-only types (std::unique_ptr
for example)
as per cppreference
template< class ValueType >
any( ValueType&& value );
Constructs an object with initial content an object of type
std::decay_t< ValueType>
, direct-initialized fromstd::forward< ValueType>(value)
. Ifstd::is_copy_constructible< std::decay_t< ValueType>>::value
isfalse
, the program is ill-formed
You can check that is_copy_constructible ... is false with a static_assert, see on coliru
Easiest workaround I can think of is to use shared_ptr instead and still call the std::move.