mardi 25 décembre 2018

“Downcasting” unique_ptr to unique_ptr

“Downcasting” unique_ptr< Base > to unique_ptr< Derived > offer an elegent solution to downcasting unique_ptr. It works in most of time. But when the Derived contains unique_ptr, something go wrong:

template<typename Derived, typename Base, typename Del>
std::unique_ptr<Derived, Del> 
static_unique_ptr_cast( std::unique_ptr<Base, Del>&& p )
{
    auto d = static_cast<Derived *>(p.release());
    return std::unique_ptr<Derived, Del>(d, std::move(p.get_deleter()));
} 

struct Data
{
   int data;
};

struct Base
{
};

struct Derived : public Base
{
    Derived() 
        : data(std::make_unique<Data>())

    std::unique_ptr<Data> data;
}

int main()
{
    std::unique_ptr<Base> base = std::make_unique<Derived>();

    auto derived = static_unique_ptr_case<Derived>(std::move(base))->data; // compile error

    return 0;
}

Is there a better way to fix the problem?

Aucun commentaire:

Enregistrer un commentaire