struct Foo {
void setBar(bool bar_) { bar = bar_; }
bool bar;
};
int main() {
Foo f;
f.setBar("true");
}
The above code compiles successfully due to type conversion, even though a char array is passed where a bool
is expected.
Is it possible to cause this code to fail compilation? (C++03 solution preferred, since the compiler at my workplace is ancient.)
I have looked at the following related questions on StackOverflow, but they don't quite address this problem. Preventing implicit conversion in C++, Why does the compiler choose bool over string for implicit typecast of L""?
You can declare a function that takes
const char*
and don't provide a definition:This will make it fail at link time. You're still left will all other implicit conversion, though - from any pointer to bool, integral to bool, floats to bool...
Another option:
This way you'll get an error about it being private if you call it with anything else than
bool
.There is a common idiom that both avoids this issue and provides other advantages. Instead of using
bool
, you can create a custom type that more clearly describes the state that it represents.The type
bool
represents only a generic value oftrue
orfalse
, while in actual usage you are overloading these states to mean something more specific. Here's an example using an enum to define a new type:This still allows implicit conversion from any arithmetic or floating type. To avoid this, you can use C++11's
enum class
, or roll your own strongly-typed bool like this:One option would be to make
setBar
a template, and allow it only to work withbool
:Alternatively, you can use SFINAE with
std::enable_if
to the same effect, although the compiler warning might be less easy to read: