1
votes

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
"char being automatically converted to bool makes sense, but not the other way around." Are you sure? Seems opposite to me. Every bool fits in a char but not the other way around. - cigien
What are you using to compile? - JohnFilleau
@TedLyngmo sorry miss-read your comment didn't realise you quoting the OP. - Richard Critten
char test = strict<char>(true); will fail to compile. Just need to make the strict template class that disallows anything that not the type. - Eljay
The best answer I believe is: live with it. It is a choice C++ made long ago. It's not great, but fighting against it is even worse. - Passer By

3 Answers

3
votes

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.

2
votes

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.

-3
votes

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