简体   繁体   中英

C++ array of member function pointers?

Been using the website for a long time and it's answered countless questions for me. I've been programming for a long time, but I'm new to C++. This is my first question here.

I need to have an array that holds member function pointers. The functions that the array will be pointing to have the same arguments and return type, but are members of DIFFERENT classes. Is it possible to store pointers to member functions of different classes in the same array?

Assuming you what to literally store pointers of pointer-to-member type in your array, the answer is: it depends. It depends on whether there is a hierarchical relationship between your classes.

If your classes are completely unrelated, then you can only reinterpret_cast your pointers to some common type, like void (SomeArbitraryClass::*)() and then reinterpret_cast them back to their original types when performing the call. This is basically a "no" answer, since this is little more than a rather ugly hack.

(Alternatively, as Dietmar Kühl suggested, you can use type-erasure techniques, like the one offered by std::function<> in C++11 to store callable objects in your array. Such objects will not be pointers-to-member anymore though.)

But if your classes are members of the same class hierarchy, then you can rely on the fact that in C++ class member pointers are contravariant . This means that pointer to member of base class can be implicitly converted to pointer to member of derived class. And even though they don't convert implicitly in the reverse direction, the language supports this conversion through static_cast . So, you have to give the array elements the type R (CommonBaseClass::*)(Args) and use static_cast to that type when filling in the array. In this case you don't have to convert these pointers back to original type when performing the call - the language will do everything correctly by itself (assuming you supply objects of correct type at the moment of pointer dereference).

You can consider the object of the class an additional argument into the member function (basically, what becomes the this pointer). Since the member functions, thus, all get different argument types, you can't store them in an array directly. You could, however, type-erase the class type using something like std::function<RC(Args)> . When you have members for different classes, you probably need to provide suitable objects which can be bound to the member functions using std::bind() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM