简体   繁体   English

std :: unique_ptr和一个模板

[英]std::unique_ptr and a template

I have a scenario where I use CRTP. 我有一个使用CRTP的方案。 Pseudo code below: 伪代码如下:

template <typename T>
class Base {} 

class Derived1 : Base < Derived1 >  {}

class Derived2 : Base < Derived2 > {} 

everything works fine except when I introduce unique_ptr in to the loop. 一切正常,除非在循环中引入unique_ptr I want to have a unique_ptr to Base and elsewhere in the code use this to take ownership of either a Derived1 or Derived2 pointer. 我想对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());

or 要么

base_unique_ptr.reset(new Derived2());

Am I in trouble? 我有麻烦吗? I don't want to change the existing codes use of unique_ptr . 我不想更改现有代码对unique_ptr使用。

Base isnt a proper type. Base不是正确的类型。 You need to specify the template argument for Base . 您需要为Base指定模板参数。 I assume you want base_unique_ptr for Derived1 and Derived2, which is not possible since they have different base classes. 我想,你希望base_unique_ptr为Derived1和Derived2的,因为他们有不同的基类这是不可能的。 Base<Derived1> and Base<Derived2> are differnet types. Base<Derived1>Base<Derived2>是不同的网络类型。

It doesn't work because Base is not a type. 因为Base不是类型,所以它不起作用。 You can use std::unique_ptr<Base<Derived1>> for example to point to objects of that type. 例如,您可以使用std::unique_ptr<Base<Derived1>>指向该类型的对象。 Also, the inheritance is private, so the derived pointer wouldn't be convertible to the parent. 另外,继承是私有的,因此派生的指针将不能转换为父代。

If you want to have a pointer that can point to any instance of the class template, then you can give them a common base by inheriting the template from a non-tamplate base class. 如果您想要一个可以指向类模板任何实例的指针,则可以通过从非模板模板基类继承模板来为它们提供通用的基础。

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