无法移动std :: any [英] Cannot move std::any
问题描述
以下代码
using vptr = std::vector<std::unique_ptr<int>>;
auto m = std::unordered_map<int, std::any>{};
m.try_emplace(0, move(vptr{}));
无法编译,抱怨使用了已删除的unique_ptr
复制构造函数.在模板参数中将std::any
替换为vptr
后,此代码将编译,因此问题很明显是any
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
如何强制移动std::any
而不是复制?
How can I force std::any
to be moved instead of copied?
推荐答案
问题不是移动std :: any,这是因为std :: any本身不支持仅移动类型(例如std :: unique_ptr)
The problem is not moving std::any, it's that std::any itself does not support move-only types (std::unique_ptr for example)
按照 cppreference
template< class ValueType >
any( ValueType&& value );
使用初始内容构造一个对象,该对象的类型为直接从
std::forward< ValueType>(value)
初始化的std::decay_t< ValueType>
类型的对象. 如果std::is_copy_constructible< std::decay_t< ValueType>>::value
是false
,则表明程序格式错误
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
您可以使用static_assert检查is_copy_constructible ...是否为假,请参见 coliru
You can check that is_copy_constructible ... is false with a static_assert, see on coliru
我能想到的最简单的解决方法是改用shared_ptr并仍然调用std :: move.
Easiest workaround I can think of is to use shared_ptr instead and still call the std::move.
这篇关于无法移动std :: any的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!