无法移动std :: any

Ryb*_*yba 0 c++ move move-semantics c++17 stdany

以下代码

using vptr = std::vector<std::unique_ptr<int>>;
auto m = std::unordered_map<int, std::any>{};
m.try_emplace(0, move(vptr{}));
Run Code Online (Sandbox Code Playgroud)

无法编译,抱怨使用的已删除副本构造函数unique_ptr。在模板参数中替换std::any为之后,vptr此代码将编译,因此问题显然与any

如何强制std::any移动而不是复制?

Dav*_*vid 5

问题不是移动std :: any,而是std :: any本身不支持仅移动类型(例如std :: unique_ptr)

按照cppreference

template< class ValueType >
any( ValueType&& value );
Run Code Online (Sandbox Code Playgroud)

构造一个具有初始内容的对象,该对象的初始类型为std::decay_t< ValueType>,直接从初始化std::forward< ValueType>(value)如果std::is_copy_constructible< std::decay_t< ValueType>>::valuefalse,则程序格式错误

您可以使用static_assert检查is_copy_constructible ...是否为false,请参阅coliru

我能想到的最简单的解决方法是改用shared_ptr并仍然调用std :: move。