lundi 25 mai 2015

How do I cast between subclasses of shared_ptr?

I'm subclassing std::shared_ptr and am trying to write a cast() method on the subclass so I can hide static_pointer_cast, but I can't get my code to compile. What am I missing?

Demo: http://ift.tt/1LwURVV

template<class T>
class Handle : public std::shared_ptr<T> {
public:
    template<class ResultType>
    inline Handle<ResultType>
    cast() {
        // Cast Handle to shared_ptr
        auto T_sp = static_cast< std::shared_ptr<T> >(*this);
        // Cast the data
        auto ResultType_sp = std::static_pointer_cast<ResultType>(T_sp);
        // Cast back to Handle
        return static_cast< Handle<ResultType> >(ResultType_sp);
    }
};


// Usage
struct Base {};
struct Child : public Base {};
auto child_ptr = Handle<Child>(new Child());
auto base_ptr  = child_ptr.cast<Base>(); // Error with this

This is the Error message I get:

error: no matching function for call to 'Handle<Child>::Handle(Child*)'
auto child_ptr = Handle<Child>(new Child());
                                         ^

Aucun commentaire:

Enregistrer un commentaire