How to generate warning when using static_cast in c++ gcc?

182 views Asked by At

I need to remove the use of static_cast from the project and prevent normal compilation if static_cast is added, the gcc documentation doesn't say how warnings can be enabled when using static_cast.

I searched the gcc documentation for the static_cast keyword, but did not find anything suitable.

2

There are 2 answers

2
user17732522 On

I highly doubt that there is any compiler setting for that in general. static_cast is a completely normal feature of the language to use and the preferred way over C-style explicit casts. It is not clear what purpose such a warning would serve. In fact static_cast is conventionally used to tell the compiler to not warn about otherwise implicit conversions that might be problematic like narrowing conversions.

There is a clang-tidy check cppcoreguidelines-pro-type-static-cast-downcast to warn of uses of static_cast that are downcasts (which may lead to UB and are recommended by the core guidelines to be replaced with dynamic_cast).

Maybe there is also some clang-tidy check or similar that warns if a static_cast conversion would also be possible implicitly, but that would probably interfere with the convention mentioned above.

You'll likely need to use an external tool. Something as simple as grep -R static_assert . or some sed/awk to replace uses of static_assert in the way you want may be sufficient. If you need to actually modify the parsed AST, you'll probably need to write something e.g. based on Clang's libraries/tooling.

5
armagedescu On

It can be blocked by #define.
This will generate a compile error

#define static_cast
int main()
{
    int x = static_cast<int> (3.14);
}