Search code examples
c++shared-ptrstdbind

Parallel of std::reference_wrapper for std::shared_ptrs


If you want to bind a reference to a function f, you can use std::bind(f, std::ref(x)). In this case f takes a reference or makes a copy.

Now I have a function void g(T & t). I would like to bind the input argument to std::shared_ptr<T> mySharedPtr like this: std::bind(g, mySharedPtr). This would guarantee that mySharedPtr's data would have a lifetime at least as long as the bind. But since g takes a reference, this does not type-check.

Is there something similar to std::ref that takes a std::shared_ptr and dereferences it before passing it into g? If not, could I make one myself?

(If you give an answer using lambdas, please also include one without lambdas since my compiler does not support them.)

Edit: std::bind(g, std::ref(*mySharedPtr)) does not work since it loses the lifetime guarantee of the std::shared_ptr.


Solution

  • It seems you could create a deref() function which would create an object dereferencing something looking like a pointer upon conversion:

    template <typename P>
    class pointer_wrapper {
        P ptr;
    public:
        pointer_wrapper(P p): ptr(p) {}
        operator decltype(*std::declval<P>())&() {
            return *ptr;
        }
    };
    template <typename P>
    pointer_wrapper<P> deref(P p) {
        return p;
    }
    

    It may be better to make the conversion a member template to allow a few more conversions.