0

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?

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
Ryba
  • 681
  • 4
  • 13

1 Answers1

5

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 from std::forward< ValueType>(value). If std::is_copy_constructible< std::decay_t< ValueType>>::value is false, 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.

Barry
  • 286,269
  • 29
  • 621
  • 977
David
  • 602
  • 5
  • 14