我在尝试对从其他类型派生的模板化类型使用 std::move
语义时遇到问题。也就是说,我在以下示例中遇到错误。
#include <memory>
template <typename T>
class A{
};
template <typename T>
class B:A<T>{
};
int main()
{
std::unique_ptr<B<int> > bar(new B<int>());
std::unique_ptr<A<int> > foo (std::move(bar));
}
错误出现在定义 foo 的行上,它是:
In function 'int main()':
17:47: error: no matching function for call to 'std::unique_ptr<A<int> >::unique_ptr(std::remove_reference<std::unique_ptr<B<int> >&>::type)'
显然,非模板化的等效项工作得很好。
最佳答案
B
私有(private)地继承自 A
,因此不存在从 B
到 A
的可用转换。更改为 public
继承,您的代码将可以编译。
template <typename T>
class B: public A<T>{};
// ^^^^^^
在您的示例中,A
的析构函数应该是virtual
,否则您将拥有 undefined behavior当 foo
超出范围时,因为您将尝试通过 A *
删除
B
实例。
关于c++ - 在 C++1y 中从模板化基派生的类型上对 unique_ptr 使用 std::move,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33092009/