Skip to content

Instantly share code, notes, and snippets.

@AndrewTsao
Created May 17, 2015 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewTsao/a626108d1d15efce7286 to your computer and use it in GitHub Desktop.
Save AndrewTsao/a626108d1d15efce7286 to your computer and use it in GitHub Desktop.
CONTAINER_OF for C++
template <class T, typename M>
T* container_of(M *m, const M T::*mp) {
static const T * null = reinterpret_cast<const T *>(null);
static const ptrdiff_t offset = reinterpret_cast<const ptrdiff_t>(&(null->*mp));
return reinterpret_cast<T*>(reinterpret_cast<char*>(m) - offset);
}
@hutorny
Copy link

hutorny commented Nov 14, 2016

I'm not sure if this is right: static const T * null = reinterpret_cast<const T *>(null);
Maybe you meant static const T * null = reinterpret_cast<const T *>(nullptr); ?
In such case I think you would have to use static_cast.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment