Conversion from boost::shared_ptr to std::shared_ptr?

后端 未结 2 1199
醉酒成梦
醉酒成梦 2020-12-04 15:37

I got a library that internally uses Boost\'s version of shared_ptr and exposes only those. For my application, I\'d like to use std::shared_ptr wh

2条回答
  •  遥遥无期
    2020-12-04 16:21

    Based on janm's response at first I did this:

    template std::shared_ptr to_std(const boost::shared_ptr &p) {
        return std::shared_ptr(p.get(), [p](...) mutable { p.reset(); });
    }
    
    template boost::shared_ptr to_boost(const std::shared_ptr &p) {
        return boost::shared_ptr(p.get(), [p](...) mutable { p.reset(); });
    }
    

    But then I realized I could do this instead:

    namespace {
        template struct Holder {
            SharedPointer p;
    
            Holder(const SharedPointer &p) : p(p) {}
            Holder(const Holder &other) : p(other.p) {}
            Holder(Holder &&other) : p(std::move(other.p)) {}
    
            void operator () (...) { p.reset(); }
        };
    }
    
    template std::shared_ptr to_std_ptr(const boost::shared_ptr &p) {
        typedef Holder> H;
        if(H *h = boost::get_deleter(p)) {
            return h->p;
        } else {
            return std::shared_ptr(p.get(), Holder>(p));
        }
    }
    
    template boost::shared_ptr to_boost_ptr(const std::shared_ptr &p){
        typedef Holder> H;
        if(H * h = std::get_deleter(p)) {
            return h->p;
        } else {
            return boost::shared_ptr(p.get(), Holder>(p));
        }
    }
    

    This solution leaves no reason for not using it without restrictions since you get the original pointer back if you convert back to the original type.

提交回复
热议问题