c++ - 将函数标记为虚拟会导致 unique_ptr 出现编译器错误

标签 c++ templates c++11 instantiation overload-resolution

我有一个包装 vector 的模板类。我试图在这个类中存储 unique_ptrs,它工作正常。但是,当我将 void add(const T& elem) 函数标记为虚拟时,我的编译器 (clang) 告诉我我正在为 unique_ptr 进行“调用隐式删除的复制构造函数”。

我知道无法复制 unique_ptr,所以我创建了 void add(T&& elem) 函数。我只是不知道为什么将另一个 add 函数标记为 virtual 会导致编译器错误。

感谢您的宝贵时间。

#include <iostream>
#include <vector>
#include <memory>

using namespace std;

template <typename T>
class ContainerWrapper {
private:
    vector<T> vec;
public:
    ContainerWrapper() : vec() {

    }

    //Marking this as virtual causes a compiler error
    void add(const T& elem) {
        vec.push_back(elem);
    }

    void add(T&& elem) {
        vec.push_back(std::move(elem));
    }

    T removeLast() {
        T last = std::move(vec.back());
        vec.pop_back();
        return last;
    }
};

int main() {
    ContainerWrapper<unique_ptr<string>> w;
    w.add(unique_ptr<string>(new string("hello")));

    unique_ptr<string> s = w.removeLast();

    cout << *s << endl;
}

最佳答案

这很可能是因为 ContainerWrapper 是一个模板。对于模板,只要您不调用成员函数,编译器通常不会检查它们。但是,将其标记为虚拟会强制该函数存在(您甚至可能会收到链接错误)。

你可以看看这篇文章:When the virtual member functions of a template class instantiated? .

关于c++ - 将函数标记为虚拟会导致 unique_ptr 出现编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14554288/

相关文章:

android - 如何提高android中的OpenCV人脸检测性能?

c++ - 处理大型数据集 - 算法结果与 1k 条目测试匹配,但在 100 万条目测试中失败 - 相同的算法

c++ - 带有模板的目标文件如何链接在一起

ajax - 加载部分模板 Ajax - 使用 Grails

c++ - 当 operator& 重载时,如何可靠地获取对象的地址?

c++ - 变量模板参数中的decltype

c++ - 在C++中将子整数保存在数组中

c++ - 无法编译 LibOTR

具有特定接口(interface)的类型的 C++ 模板特化

c++ - 命名数组元素,或 union 内的结构和数组