使用std::move在unique_ptr上对c++ 1y中模板化基类派生的类型进行操作
using std::move on unique_ptr on a type derived from templated base in C++1y
在从另一种类型派生的模板类型上使用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
私下继承A
,所以没有从B
到A
的可用转换。修改为public
继承,你的代码就可以编译了。
template <typename T>
class B: public A<T>{};
// ^^^^^^
在您的示例中,A
的析构函数应该是virtual
,否则当foo
超出作用域时,您将有未定义的行为,因为您将试图通过A *
来delete
B
实例。
问题是我正在使用私有继承。当我把B的定义改成:乙级:公共一切顺利。
我保留了另一个解决方案只是为了记录:由于没有更好的办法,我只好这样做了:
std::unique_ptr<A<int> > foo ( (A<int> * ) new B<int>());
相关文章:
- 如何通过派生类函数更改基类中的向量
- 如何使用基类指针引用派生类成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 如果基类包含双指针成员,则派生类的构造函数
- 为什么此派生对象无法访问基类的后递减方法?
- 使用基类中的派生方法运行线程,而无需使用模板
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 在派生类中使用基类的私有成员变量的最佳方法
- 基类和派生类的多态赋值运算符
- 如何在从抽象基派生的类中实现相同的方法?
- 基类的填充将被复制到派生类中
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 指向基类派生类的 std::unique_ptr 的指针
- 为什么基类数据在派生类数据之前初始化
- c++ 派生基类 Friend 函数访问父级上的私有函数
- 如何将基类替换为派生基类
- 当基类未指定构造函数时,如何使用仅具有带参数的构造函数的类派生基类?
- 解析公用派生基类模板中的函数模板名称时出错"Not declared in this scope"