繁体   English   中英

std :: unique_ptr和一个模板

[英]std::unique_ptr and a template

我有一个使用CRTP的方案。 伪代码如下:

template <typename T>
class Base {} 

class Derived1 : Base < Derived1 >  {}

class Derived2 : Base < Derived2 > {} 

一切正常,除非在循环中引入unique_ptr 我想对Base和代码中的其他地方使用unique_ptr来获取Derived1Derived2指针的所有权。

// declaration - this is the problem - wont compile.
std::unique_ptr<Base> base_unique_ptr;

// cpp , elsewhere.
base_unique_ptr.reset(new Derived1());

要么

base_unique_ptr.reset(new Derived2());

我有麻烦吗? 我不想更改现有代码对unique_ptr使用。

Base不是正确的类型。 您需要为Base指定模板参数。 我想,你希望base_unique_ptr为Derived1和Derived2的,因为他们有不同的基类这是不可能的。 Base<Derived1>Base<Derived2>是不同的网络类型。

因为Base不是类型,所以它不起作用。 例如,您可以使用std::unique_ptr<Base<Derived1>>指向该类型的对象。 另外,继承是私有的,因此派生的指针将不能转换为父代。

如果您想要一个可以指向类模板任何实例的指针,则可以通过从非模板模板基类继承模板来为它们提供通用的基础。

struct Base {
    virtual ~Base(){} // don't forget the virtual destructor
};
template<typename T>
struct TBase: Base {};
struct Derived1: TBase<Derived1> {};
struct Derived2: TBase<Derived2> {};

// elsewhere
std::unique_ptr<Base> base_unique_ptr;
base_unique_ptr.reset(new Derived1);
base_unique_ptr.reset(new Derived2);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM