以下代码
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
如何强制移动
std::any
而不是复制?
问题不在于移动
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 ... 是否为 false,请参阅 coliru
我能想到的最简单的解决方法是使用shared_ptr,并仍然调用std::move。