Prevent implicit conversion from bool to char

Viewed 367

I noticed that in C++ bool is implicitly converted to char. I realize that they're both stored as 1 byte, but they're fundamentally different types. Is there some compiler flag or something I can set to prevent an implicit conversion between the two? char being automatically converted to bool makes sense, but not the other way around.

for example, the following is valid:

char test = true;

I'm using Xcode with C++17

3 Answers

This conversion is mandated by the C++ standard (part of the integral conversions), so it is not possible to disable this conversion and remain a compliant C++ compiler.

It is possible for compilers to offer non-compliant extensions, but for something like this they would probably prefer a warning to going non-compliant. However, I was not able to find a compiler that offers such a warning (see, for example, No warning for implicit cast of bool to floating type).

Still, an answer might exist in the form of non-compiler tools. It looks like clang-tidy includes a check for implicit conversions from bool.

Here's a possible solution based on the comment by @Eljay:

template<typename T, typename U>
T strict(U u)
{
    static_assert(std::is_same_v<T, U>);
    return u;
}

and then you can use it like this:

char test  = strict<char>(true);  // error
char test  = strict<char>('a');   // ok

Here's a demo.

char is int, so conversion is ok.

if you dont want this to happen you can do function with same name, but with bool as parameter. You can do the definition only, so if you do call it with bool it will compile but wont link.

Will show you example as soon as I am on PC

Related