简体   繁体   中英

std::unique_ptr and a template

I have a scenario where I use 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. 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.

// 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 .

Base isnt a proper type. You need to specify the template argument for Base . I assume you want base_unique_ptr for Derived1 and Derived2, which is not possible since they have different base classes. Base<Derived1> and Base<Derived2> are differnet types.

It doesn't work because Base is not a type. You can use std::unique_ptr<Base<Derived1>> for example to point to objects of that type. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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