c++ - 将一对 move 到 vector 中

标签 c++ c++11 move std-pair

我有这个函数模板:

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/

相关文章:

java - C++(STL)与Java中的迭代器,有概念上的区别吗?

c++ - 将递归解决方案转换为迭代解决方案

vba - 首次运行后对共享文件夹的引用丢失

c++ - 如何使用C++中带有不可复制成员的initializer_list创建映射?

javascript - 如何在 Opera 和 Chrome 中 move 和调整浏览器窗口的大小?

c++ - 从文件中读短

c++ - 如果被虚假唤醒,消费者线程是否会收到condition_variable通知信号

c++ - 静态变量生命周期,文件范围与函数范围

c++ - shared_ptr 无法解析

c++ - 为什么 CRITICAL_SECTION 性能在 Win8 上变差