Skip to content

Instantly share code, notes, and snippets.

@gintenlabo
Created July 19, 2013 07:46
Show Gist options
  • Select an option

  • Save gintenlabo/6037428 to your computer and use it in GitHub Desktop.

Select an option

Save gintenlabo/6037428 to your computer and use it in GitHub Desktop.
get shared_ptr which referes (and has ownership of) specified data member
#include <memory>
template<class T, class C>
std::shared_ptr<T> get_shared_member(
std::shared_ptr<C> const& sp, T C::*mp) {
if (!sp) {
return {};
}
auto& x = *sp;
return std::shared_ptr<T>(sp, std::addressof(x.*mp));
}
template<class T, class C>
std::shared_ptr<T const> get_shared_member(
std::shared_ptr<C const> const& sp, T C::*mp) {
return get_shared_member(std::const_pointer_cast<C>(sp), mp);
}
struct Hoge {
int x;
int const y;
};
int main() {
auto p = std::make_shared<Hoge>(Hoge{1, 2});
std::shared_ptr<Hoge const> cp = p;
get_shared_member(p, &Hoge::x);
get_shared_member(p, &Hoge::y);
get_shared_member(cp, &Hoge::x);
get_shared_member(cp, &Hoge::y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment