class A {
public:
A() {}
void show() { }
int a;
};
void* CreateA() {
return new A();
}
int main() {
map<string, void*> mp = {
{"A",&CreateA}
};
A* a = (A*)mp["A"](); // wrong at this line
a->a = 10;
a->show();
return 0;
}
My understanding is that the address of the function is stored in the map, so calling mp["A"]() should be equivalent to CreateA(), but the compiler cannot compile it.Why ?
seeplus, your first program doesn't seem to compile using GCC and Clang.
I think the problem is that there is no implicit conversion from function pointers to void*. Doing an explicit cast seems to work but not sure if it's guaranteed by the standard.
> Doing an explicit cast seems to work but not sure if it's guaranteed by the standard.
It is not guaranteed by the standard; but
8) On some implementations (in particular, on any POSIX compatible system as required by dlsym), a function pointer can be converted to void* or any other object pointer, or vice versa. If the implementation supports conversion in both directions, conversion to the original type yields the original value, otherwise the resulting pointer cannot be dereferenced or called safely. https://en.cppreference.com/w/cpp/language/reinterpret_cast