"David Olsson" <vonolsson@gmail.com> wrote in message
news:1158322911.471685.111790@b28g2000cwb.googlegroups.com
I am writing an application in which I use pointer to member
functions to achieve a certain functionality. At one point I need to
be able to cast between different types of member function. In a
very simplified version, this is what I want to do:
class Base {
public:
typedef void (Base::*MethodPrototype)();
Base(MethodPrototype method): m_method(method) {}
void call() {
(this->*m_method)();
}
private:
MethodPrototype m_method;
};
class Derived: virtual public Base {
public:
Derived():
Base(reinterpret_cast<MethodPrototype>(&Derived::myMethod)) {}
int myMethod() {
return(1);
}
};
The constructor of the Derived class failes to compile as visual c++
reports that the reinterpret_cast is invalid. This does however only
occur when the inheritance is virtual, if it isn't virtual, the
casting works fine. Furthermore, the above code compiles with GCC
3.4.2. Is it Visual C++ or GCC that isn't quite conformant.
Comeau compiles it. Section 5.2.10/6 of the C++ standard says this
about reinterpret_cast:
"A pointer to a function can be explicitly converted to a pointer to a
function of a different type. The effect of calling a function
through a pointer to a function type (8.3.5) that is not the same as
the type used in the definition of the function is undefined. Except
that converting an rvalue of type "pointer to T1" to the type
"pointer to T2" (where T1 and T2 are function types) and back to its
original type yields the original pointer value, the result of such a
pointer conversion is unspecified. [Note: see also 4.10 for more
details of pointer conversions. ]"
The above section is for free functions. Alex has given the right section
for pointers to member functions.