Code with old style cast:
const string *ps;
void *pv;
pv = (void*)ps;
I have try three various named casts:
pv = static_cast<void*>(ps); // error: invalid static_cast from type ‘const string* {aka const std::basic_string<char>*}’ to type ‘void*’
pv = const_cast<void*>(ps); // error: invalid const_cast from type ‘const string* {aka const std::basic_string<char>*}’ to type ‘void*’
pv = reinterpret_cast<void*>(ps); // error: reinterpret_cast from type ‘const string* {aka const std::basic_string<char>*}’ to type ‘void*’ casts away qualifiers
As you can see. Nothing works.
You should const_cast
, but to the right type. The cast from string*
to void*
will then happen automatically.
pv = const_cast<string*>(ps);
In this special case, it's simply:
pv = const_cast<string*>( ps );
The conversion from string*
to void*
is implicit. If you wanted to
make it explicit, you'd need a second, separate cast:
pv = static_cast<void*>( const_cast<string*>( ps ) );
or
pv = const_cast<void*>( static_cast<void const*>( ps ) );
I don't think making it explicit is particularly necessary, however; the
fact that you're using a void*
already says that there will be
conversions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With