Crazy C++ template - A template to access individual attributes of a class

Viewed 3647

I am a novice C++ programmer, but I thought I know enough about C++ until today when I came across code like this at work and failed to understand how it actually works.

class Object
{
};

template <
        class PropObject,
        class PropType, 
        PropType PropObject::* Prop
        >
class PropReader
{
public:
    void print(Object& o)
    {
        PropObject& po = static_cast<PropObject &>(o);
        PropType& t = po.*Prop;

        cout << t << "\n";
    }
};

class Student : public Object
{
public:
    int age;
    int grade;
};

int _tmain(int argc, _TCHAR* argv[])
{   
    Student s;
    s.age = 10;
    s.grade = 5;

    PropReader<Student, int, &Student::age> r;
    PropReader<Student, int, &Student::grade> r2;

    r.print(s);
    r2.print(s);
}

I think I kind of understood at a high level. But this particular PropType PropObject::* Prop in the template declaration bothers me. What does it mean? I am looking for an explanation from C++ experts. I would like to understand it, so that I can use it better. It looks very useful though.

5 Answers
Related