将一对移动到向量中

Move a pair into vector

我有这个函数模板:

template<typename Collection, typename T>
void insertColElement(Collection col, const T& element, std::true_type)
{
    col.insert(col.end(), std::move(element));
}

如果 T 是可移动构造的,则调用它。现在我想用 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 只是一个转换,你将元素转换为a 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));
}