Pointer to class data member “::*”

后端 未结 15 1638
清歌不尽
清歌不尽 2020-11-21 11:47

I came across this strange code snippet which compiles fine:

class Car
{
    public:
    int speed;
};

int main()
{
    int Car::*pSpeed = &Car::speed;
         


        
15条回答
  •  盖世英雄少女心
    2020-11-21 12:10

    Another application are intrusive lists. The element type can tell the list what its next/prev pointers are. So the list does not use hard-coded names but can still use existing pointers:

    // say this is some existing structure. And we want to use
    // a list. We can tell it that the next pointer
    // is apple::next.
    struct apple {
        int data;
        apple * next;
    };
    
    // simple example of a minimal intrusive list. Could specify the
    // member pointer as template argument too, if we wanted:
    // template
    template
    struct List {
        List(E *E::*next_ptr):head(0), next_ptr(next_ptr) { }
    
        void add(E &e) {
            // access its next pointer by the member pointer
            e.*next_ptr = head;
            head = &e;
        }
    
        E * head;
        E *E::*next_ptr;
    };
    
    int main() {
        List lst(&apple::next);
    
        apple a;
        lst.add(a);
    }
    

提交回复
热议问题