以下代码
X
编译失败,抱怨使用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
进行移动而不是复制?
答案 0 :(得分:5)
问题不是移动std :: any,而是std :: any本身不支持仅移动类型(例如std :: unique_ptr)
template< class ValueType >
any( ValueType&& value );
将具有初始内容的对象构造为类型
std::decay_t< ValueType>
的对象,该类型从std::forward< ValueType>(value)
直接初始化。 如果std::is_copy_constructible< std::decay_t< ValueType>>::value
是false
,则说明程序格式错误
您可以使用static_assert检查is_copy_constructible ...是否为假,请参见coliru
我能想到的最简单的解决方法是改用shared_ptr并仍然调用std :: move。