What are pointers to class members used for?
I have read about pointers to class members, but I have never seen them being used in any practical applications. Can someone explain what are the use cases of such pointers? Is it really necessary to have such pointers?
Eg.
class abc
{
public:
int a;
abc(int val) { a = val; }
};
int main()
{
int abc::开发者_JAVA技巧*data;
abc obj(5);
data = &abc::a;
cout << "Value of a is " << obj.*data << endl;
return 0;
}
In the above eg. why is the value of 'a' accessed in this manner? What is the advantage of using pointers to class members?
The biggest advantage of a pointer-to-member or pointer-to-member-function is that you
- don't have to bind to a specific instance right away
- don't need to place any restrictions on the member names, only the type has to match.
This can be used for e.g. call-backs or abstract algorithms:
std::map<int,int> m;
m.insert(std::make_pair(1,2));
m.insert(std::make_pair(3,4));
m.insert(std::make_pair(5,6));
std::ptrdiff_t s =
std::count_if(m.begin(), m.end(),
boost::bind(&std::map<int,int>::value_type::first, _1) > 2);
std::cout << s << std::endl; // 2
Note that Boost.Bind, Boost.Function and their TR1 equivalents already encapsulate that nicely for you. To a certain degree the current standard also includes tools like std::mem_fun
in <functional>
.
If you have used MFC, you will see pointers to member function concept is heavily used (internally)
DECLARE_MESSAGE_MAP, BEGIN_MESSAGE_MAP, END_MESSAGE_MAP See Message Maps
The question I suppose is: "what does pointer to member data add over simple pointer to data?" and the only answer I can think of is a level of explicit meaning: we are pointing at data in this class.
Now I can see some value in what is effectively some additional documentation of intent. One example I've seen that might be quite powerful is when our "class" is actually a legacy C struct. Now we have no local methods of that struct, so having some pointers that are explicitly associated with that struct may well make our code clearer.
Pointer-to-member is, like all C++ features, just syntactic sugar for something you could already have done in pure C.
Pointers-to-member-variable are pretty simple. One use case is if you wanted to write a (template) function that could sort an array of structures by any field. By passing in a pointer-to-member, you can retrieve some specified field of any instance of the structure without having to hard-code the field. Of course a functor that accepts a structure pointer and returns the field value could have been used instead.
Pointers-to-member-function are a little more complicated. At first glance, they are just like ordinary function pointers that know how to pass the hidden 'this' pointer. But virtual functions make a simple idea pretty complicated.
And virtual base classes make all pointers-to-member awfully complicated. It's not something you'd want to code yourself using simple C constructs. But the complex cases are rare.
精彩评论