我有这个函数模板:
template<typename Collection, typename T>
void insertColElement(Collection col, const T& element, std::true_type)
{
col.insert(col.end(), std::move(element));
}
如果 T 是可 move 构造的,则调用它。现在我想用 Collection = std::vector<..>
调用这个函数和 T = std::pair<std::unique_ptr<..>, bool>
,但编译器提示删除了 unique_ptr 和 pair 的复制构造函数。我已经尝试使用 emplace 并分别 move first 和 second,但编译器仍想调用复制构造函数。
编辑:
以下是所有相关的代码片段:
template<typename Collection, typename T>
void insertColElement(Collection col, T&& element, std::true_type)
{
col.insert(col.end(), std::forward<T>(element));
}
template<typename Collection, typename T>
void insertColElement(Collection col, T& element, std::false_type)
{
static_assert(std::is_copy_constructible<T>::value,
"Serialization: Collection type is neither copy nor move constructable");
col.insert(col.end(), element);
}
template<typename Archive, typename Collection>
inline void loadCollection(Archive& ar, Collection& col)
{
int size;
ar >> size;
for(int i = 0; i < size; i++) {
typename Collection::value_type element;
ar >> element;
insertColElement(col, std::move(element),
typename std::is_move_constructible<typename Collection::value_type>::type());
}
}
这些函数是我正在使用的一个小型序列化模块的一部分。 loadCollection
用于从 Archiv 加载容器。导致问题的调用如下所示:
IStreamArchive a(filestream);
std::vector<std::pair<std::unique_ptr<Scope>, bool>> vec;
a << vec;
最佳答案
你不能从 const 的东西中 move ,所以即使你写了 move()
(因为 move
只是一个cast,你将元素转换为 const T&&
。没有 const T&&
构造函数,并且 T&&
构造函数不匹配,所以接下来最佳匹配是 const T&
构造函数)。这就是问题所在。
您应该改为编写以下内容:
template<typename Collection, typename T>
void insertColElement(Collection& col, T&& element, std::true_type)
{
col.insert(col.end(), std::forward<T>(element));
}
关于c++ - 将一对 move 到 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32462435/