Bob
Bob

Reputation: 1455

Why cant i use static_cast<const char**>(str) instead of (const char**)str?

I have an issue, it doesn't want to cast using static_cast<>. What can it be?

void myCompare(const void *str)
{
    const char *ca = *(static_cast<const char**>(str)); //error
    const char *a = *(const char **)str; //ok
}

Upvotes: 1

Views: 359

Answers (1)

Columbo
Columbo

Reputation: 60979

You're casting away const on the second level, which static_cast is not allowed to do (in fact, no "C++" cast apart from const_cast):

          void    const*
   char const*         *
// ^^^^^^^^^^^    ^^^^^
// pointee        cv-qualifiers
//                of pointee

Instead, write

const char *ca = *(static_cast<const char* const*>(str));

The (char const**) cast works here because it is equivalent to a static_cast followed by a const_cast (as per [expr.cast]/(4.3)) - i.e. it was equivalent to

const char *ca = *(const_cast<const char**>(static_cast<const char* const*>(str)));

Upvotes: 5

Related Questions