Created
October 17, 2017 14:00
-
-
Save xymopen/352cbb55ddc2a767ed7c5999cfed4d31 to your computer and use it in GitHub Desktop.
C++ equivalences of the famous offset_of and container_of(owner_of) macro from Linux kernel
This file contains hidden or 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, class M > | |
static inline constexpr ptrdiff_t offset_of( const M T::*member ) { | |
return reinterpret_cast< ptrdiff_t >( &( reinterpret_cast< T* >( 0 )->*member ) ); | |
} | |
template< class T, class M > | |
static inline constexpr T* owner_of( M *ptr, const M T::*member ) { | |
return reinterpret_cast< T* >( reinterpret_cast< intptr_t >( ptr ) - offset_of( member ) ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@SayanNS Hi, I've upload the sketch using the snippet. You can see how it was used in the kenerl-list class. In general, this snippet is used to implement intrusive containers, where dynamic memory allocation is strongly discouraged, such as an OS kernel.