This article lists all the different categories of pointers. I have tested the explicit conversion of different types of pointers to const void*
in the following snippet (live):
#include <print>
int var {};
void foo()
{
}
struct Bar
{
char mem;
void func()
{
}
};
Bar b {};
int main()
{
// nullptr
std::println( "{}", static_cast<const void*>( nullptr ) );
// pointer to object
std::println( "{}", static_cast<const void*>( &var ) );
// pointer to function
std::println( "{}", reinterpret_cast<const void*>( &foo ) );
// pointer to member variable
std::println( "{}", static_cast<const void*>( &Bar::mem ) ); // doesn t compile
std::println( "{}", static_cast<const void*>( &(b.mem) ) );
std::println( "{}", static_cast<const void*>( &(b.*(&Bar::mem)) ) );
// pointer to member function
std::println( "{}", reinterpret_cast<const void*>( &Bar::func ) ); // compiles with a warning
std::println( "{}", reinterpret_cast<const void*>( &(b.func) ) ); // doesn t compile
std::println( "{}", reinterpret_cast<const void*>( &(b.*(&Bar::func)) ) ); // doesn t compile
// Did I miss any other category?
}
现在我有几个问题:
- I want to know why
static_cast<const void*>( &Bar::mem ) );
does not compile (since&(b.*(&Bar::mem))
does). The compiler says:
error: invalid static_cast from type char Bar::* to type const void*
- Also I want to know why it s not allowed to take the address of member functions (as seen in the last three statements). The compiler says:
ISO C++ forbids taking the address of a bound member function to form a pointer to member function. Say &Bar::func
- Finally, which pointer types are we allowed to take (at least for trivial tasks like printing) without invoking errors or UB? It seems to me that pointer to member function is not allowed.