0

以下代码

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::anyvptr此代码将编译,因此问题显然在于any

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

4

1 回答 1

5

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

根据cppreference

template< class ValueType >
any( ValueType&& value );

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

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

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

于 2019-05-29T23:50:51.127 回答