Skip to content

Instantly share code, notes, and snippets.

@ompugao
Forked from xymopen/linux_magic.cpp
Created August 15, 2020 15:30
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 ompugao/9a7f03004e77f4aad94f0c04c511fc99 to your computer and use it in GitHub Desktop.
Save ompugao/9a7f03004e77f4aad94f0c04c511fc99 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
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 ) );
}
@ompugao
Copy link
Author

ompugao commented Nov 13, 2021

@ompugao
Copy link
Author

ompugao commented Nov 13, 2021

// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
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 ) );
}
class Hoge {
public:
    Hoge(int _i): i(_i) {
    }
    virtual ~Hoge() {
    }
    int i;
};

int main()
{
    std::cout << "Hello, Wandbox!" << std::endl;
    Hoge* hoge = new Hoge(10);
    int* z = &hoge->i;
    Hoge* h = owner_of(z, &Hoge::i);
    std::cout << h->i << std::endl;
}

// GCC reference:
//   https://gcc.gnu.org/

// C++ language references:
//   https://cppreference.com/
//   https://isocpp.org/
//   http://www.open-std.org/jtc1/sc22/wg21/

// Boost libraries references:
//   https://www.boost.org/doc/

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