Pointer to class data member “::*”

后端 未结 15 1631
清歌不尽
清歌不尽 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:05

    Here is an example where pointer to data members could be useful:

    #include 
    #include 
    #include 
    
    template 
    typename Container::value_type searchByDataMember (const Container& container, const T& t, DataPtr ptr) {
        for (const typename Container::value_type& x : container) {
            if (x->*ptr == t)
                return x;
        }
        return typename Container::value_type{};
    }
    
    struct Object {
        int ID, value;
        std::string name;
        Object (int i, int v, const std::string& n) : ID(i), value(v), name(n) {}
    };
    
    std::list objects { new Object(5,6,"Sam"), new Object(11,7,"Mark"), new Object(9,12,"Rob"),
        new Object(2,11,"Tom"), new Object(15,16,"John") };
    
    int main() {
        const Object* object = searchByDataMember (objects, 11, &Object::value);
        std::cout << object->name << '\n';  // Tom
    }
    

提交回复
热议问题