无法移动std :: any

时间:2019-05-29 22:12:56

标签: c++ c++17 move move-semantics stdany

以下代码

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进行移动而不是复制?

1 个答案:

答案 0 :(得分: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。