Created
May 17, 2015 14:35
-
-
Save AndrewTsao/a626108d1d15efce7286 to your computer and use it in GitHub Desktop.
CONTAINER_OF for C++
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
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.