3

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.

4

1 回答 1

2

似乎您可以创建一个deref()函数,该函数将创建一个对象,该对象在转换时取消引用看起来像指针的东西:

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;
}

将转换设为成员模板以允许更多转换可能会更好。

于 2013-08-17T18:29:31.620 回答