【发布时间】:2013-01-11 08:01:17
【问题描述】:
我有一个包装矢量的模板类。我正在尝试将 unique_ptrs 存储在此类中,并且效果很好。但是,当我将 void add(const T& elem) 函数标记为虚拟函数时,我的编译器 (clang) 告诉我,我正在为 unique_ptr 进行“调用隐式删除的复制构造函数”。
我知道 unique_ptrs 不能被复制,所以这就是我创建 void add(T&& elem) 函数的原因。我只是不知道为什么将另一个添加函数标记为虚拟会导致编译器错误。
感谢您的宝贵时间。
#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;
}
【问题讨论】:
-
顺便说一句,你的整个构造函数是不必要的。
标签: c++ templates c++11 instantiation overload-resolution