I always thought that when I converted a member function ptr in C to a member function ptr in A, I just had to make sure that the call was pointing to an C entity , but that was a mistake. Does the standard describe this use case in more detail?(checked with multiple compilers,MSVC GCC error,clang pass,This could be a compiler bug or undefined behavior?)
struct A
{
char i[7];
void test1(){
std::cout << __LINE__;
}
};
struct B
{
char i[14];
virtual void test(){
std::cout << __LINE__;
}
};
struct C:A,B
{
char i[31];
};
using T = void (C::*)();
int main()
{
C c;
(c.*T(&B::test))();//good
(c.*static_cast<decltype(&A::test1)>(T(&B::test)))();//crash
return 0;
}
warning C4407: cast between different pointer to member representations, compiler may generate incorrect code
.&A::test1
is not an "address". You code smells like the ill-formed codechar c = 'a'; int* p = static_cast<int*>(static_cast<void*>(&c)); *p = 0;
.&B::test
is a pointer-to-member-of-B. You can convert it, with a cast, into a pointer-to-member-of-A, even thoughB::test
is not a member ofA
, but you cannot use the result of that cast without converting it back to its original type.