Cannot move std::any

坚强是说给别人听的谎言 提交于 2020-01-16 18:01:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/56369214/cannot-move-stdany

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!