Is it possible to prevent implicit bool <-> int conversions?

30 views Asked by At

Given this code:

void foo(int bar, bool stuff)
{
}

enum class Mode
{ 
  SomeMode_1,  SomeMode_2,
};

void foo2(int bar, Mode stuff)
{
}

int main()
{
  foo(1, true);              // (1) compiles as expected
  foo(true, 2);              // (2) compiles as expected, but unwanted
  foo2(1, Mode::SomeMode_1); // (3) compiles as expected

  foo2(1, 1);                // (4) does not compile as expected
  foo(1, Mode::SomeMode_1);  // (5) does not compile as expected
  foo(Mode::SomeMode_1, 1);  // (6) does not compile as expected
}

In case (2) the arguments have inadvertently been swapped, but it compiles because of bool and int being converted implicitly to each other.

Should I change the signature of void foo(int bar, bool stuff) and rather use a class enum instead of a bool for type safety? Or is there any other method to prevent the implicit conversion of bool to integral types and vice versa?

0

There are 0 answers