Getting object from pointer to data member

Discussion in 'C++' started by Salvo Isaja, Oct 10, 2009.

  1. Salvo Isaja

    Salvo Isaja Guest

    Greetings,
    this is my first post here, please be forgiving ;)

    I'm developing an embedded operating system in C++, and I'm writing my
    own small library for intrusive data structures. I'd like to use a
    hook member to store bookkeeping, inspired from Boost.Intrusive:
    http://www.boost.org/doc/libs/1_35_0/doc/html/intrusive/usage.html#intrusive.usage.usage_member_hook

    When the data structure user instantiates the class template, it
    specifies the node type and the address of the hook member, such as:

    class MyDataStructureHook
    {
    private:
    // pointers to other MyDataStructureHook's
    };

    template <typename T, MyDataStructureHook T::* H>
    class MyDataStructure
    {
    public:
    // ctors, dtors and other members
    void push(T& x);
    void pop();
    T& top() const;
    private:
    MyDataStructureHook* top_;
    };

    struct MyNode
    {
    int somePayload_;
    MyDataStructureHook hook_;
    bool operator<(const MyNode& x);
    };

    MyDataStructure<MyNode, &MyNode::hook_> myDataStructure;


    I know I can easily get a pointer to the hook member given a MyNode
    object, for example in push(), using MyDataStructureHook* h = &(x.*H);

    I wonder how I can do the opposite, for example in top(), to return a
    T& from MyDataStructureHook* top_. I see the Boost.Intrusive
    implementation is compiler-dependent, and it uses casts to char (boost/
    intrusive/detail/parent_from_member.hpp), and I know I could get away
    putting a T& owner_ in MyDataStructureHook. I wonder if there is a
    reliable, simple and portable way to do that without adding further
    bookkeeping.

    For the record, I'm using GCC 4.3 on Debian Testing on x86, and as I
    first try I was tempted to mess with addresses (sizeof(MyNode::*) == 4
    and &MyNode.hook_ == 4 here).

    Thank you,
    Salvo
    --
     
    Salvo Isaja, Oct 10, 2009
    #1
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Newsgroup - Ann
    Replies:
    5
    Views:
    882
    John Carson
    Jul 30, 2003
  2. slide_o_mix
    Replies:
    0
    Views:
    578
    slide_o_mix
    Oct 15, 2003
  3. Alex
    Replies:
    0
    Views:
    532
  4. Fraser Ross
    Replies:
    4
    Views:
    1,314
    Fraser Ross
    Aug 14, 2004
  5. Jason
    Replies:
    2
    Views:
    785
    Jonathan Mcdougall
    May 13, 2006
  6. Stephen Howe
    Replies:
    2
    Views:
    496
    Stephen Howe
    Nov 6, 2012
  7. somenath
    Replies:
    10
    Views:
    511
    James Kanze
    Jul 2, 2013
  8. somenath
    Replies:
    2
    Views:
    344
    somenath
    Aug 29, 2013
Loading...