Skip to content

Instantly share code, notes, and snippets.

@pallas
Last active November 22, 2016 04:05
Show Gist options
  • Save pallas/10023808 to your computer and use it in GitHub Desktop.
Save pallas/10023808 to your computer and use it in GitHub Desktop.
C++ member-to-object for classes with standard layout
// All rights reserved,
// Derrick Pallas
// License: zlib
#ifndef CONTAINER_OF
#define CONTAINER_OF
#include <cstddef>
template <class T, typename M>
T & container_of(M & m, const M T::*mp) {
static const T * null = reinterpret_cast<const T *>(NULL);
const ptrdiff_t offset = reinterpret_cast<const ptrdiff_t>(&(null->*mp));
return *reinterpret_cast<T*>(reinterpret_cast<char*>(&m) - offset);
}
#endif//CONTAINER_OF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment