ich ziemlich überrascht bin, dass diese struct
, die nur explizit umwandelbar bool
ist, in einer if
Anweisung funktioniert:Explizite und implizite Konvertierung
struct A
{
explicit operator bool() const
{
return m_i % 2 == 0;
}
int m_i;
};
int main()
{
A a{ 10 };
if (a) // this is considered explicit
{
bool b = a; // this is considered implicit
// and therefore does not compile
}
return 0;
}
Warum ist es so? Was ist der Entwurfsgrund im C++ Standard? Ich persönlich finde die zweite Konvertierung expliziter als die erste. Um es noch deutlicher, hätte ich den Compiler erwartet zwingt die folgenden haben für beide Fälle:
int main()
{
A a{ 10 };
if ((bool)a)
{
bool b = (bool)a;
}
return 0;
}
Ja, innerhalb 'if' ist wie eine explizite Konvertierung zu bool. (Sie können nicht expliziter sein als 'if' in' bool' zu konvertieren!). http://en.cppreference.com/w/cpp/language/explicit – alfC