Implicit conversion from const char* to bool

  • A+
Category:Languages

consider following code:

void foo(bool parameter) {     std::cout << parameter << "/n"; }  int main() {     foo("const char *argument"); } 

I want compiler raise warning, when passing const char* instead of bool as parameter to function foo. But GCC implicitly converts it. I tried -Wall, -Wextra, -Wpedantic, nothing works. Is there any flag that, could catch such implicit conversion (invalid parameter type)?

Ignore the fact function has argument of type bool - which may be found by some as bad code-styling, I can't refactor that part.

Standard just mentions such conversion will occur: https://en.cppreference.com/w/cpp/language/implicit_conversion

A prvalue of integral, floating-point, unscoped enumeration, pointer, and pointer-to-member types can be converted to a prvalue of type bool.

I know such behavior is very convenient in if (ptr) statements, but in case of passing parameters, for me is clearly wrong.

 


You could declare an overload of foo for pointers as deleted:

template <class T> void foo(T*) = delete; 

Or better yet, as @Ted comments, simply declare a vanilla overload to not compile any implicit conversions:

template <class T> void foo(T) = delete; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: