What i’m trying to do is somewhat obscure, so let me show on an example (this is not the actual code):
template <class T>
class ArrayStorage {
protected:
void processStuff(void (ArrayStorage<T>::*procedure)(T *)) {
for (int i = 0; i < count; i++)
(this->*procedure)(content[i]);
}
// No method of type void (ArrayStorage<T>::*)(T *)
private:
T **content;
int count;
};
class DrawableStorage : public ArrayStorage<Drawable> {
public:
void drawStuff() {
processStuff((void (ArrayStorage<Drawable>::*)(Drawable *)) &DrawableStorage::drawOne);
}
private:
void drawOne(Drawable *item) {
item->draw();
}
};
Basically, there is a generic container that is able to iterate through its items and use a method on each of them (whose pointer is in the parameter). This method however does not exist in this class, but only in its subclasses. You can see that in the subclass “drawStuff” method, i supply a method pointer of the sublass, but typecasted as a method of the base class.
Suprisingly enough, this has successfully compiled and works just fine.
My question is, is it just a coincidence that my particular compiler was able to handle it while in fact it is completely invalid and i should get rid of it, or is it correct usage of method pointers?
Thank you.
It is legal according to $5.2.9/12:
However if you try to do this with multiple inheritance or virtual inheritance, that’s when things start to break, because not all compilers implement member function pointers in a standard compliant way. On MSVC and Intel compilers all member function pointers do not have the same size, so you will lose crucial information on conversions.