The dashboard showed "6 connections" where there was one. Someone wrote conn + 5, the compiler turned the connection into 1 — and the code compiled without a single warning. The class allows the bool conversion to happen implicitly, anywhere.
The class converts to bool on its own, so even conn + 5 compiles. Add one keyword so that if (conn) still works, but arithmetic with a connection no longer compiles.
if (conn), while (conn) and !conn must still work (contextual conversion)conn + 1, int x = conn and bool b = conn must NOT compileisOpen() workaroundoperator bool make conn + 5 legal?explicit allow in an if condition that it forbids elsewhere? (contextual conversion)explicit operator bool the idiom in every serious codebase (streams, smart pointers)?You do not need to forbid the conversion — only to stop it from happening implicitly. One keyword on the operator does it.
An explicit operator bool is still used automatically in if, while, ! and && — the standard calls this "contextual conversion".
Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.