Last active
November 22, 2016 04:05
-
-
Save pallas/10023808 to your computer and use it in GitHub Desktop.
C++ member-to-object for classes with standard layout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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