Straustup mentions in his discussion that direct initialization, such as
Sick s2(2.1);
will only consider constructors with the explicit label if there are any explicit constructors. This is not my experience working with multiple compilers (including GCC 4.6.1 and MSVC 16 / VS 2010), and I cannot find such a requirement in the standard (although I would be interested if someone could point to it).
However, if ints are used in initializers, I think the example will show what Straustrup wanted to demonstrate:
#include <iostream> struct Sick { Sick(double d) { std::cout << "double " << d << "\n"; } explicit Sick(int i) { std::cout << "int " << i << "\n"; } }; int main() { Sick s1 = 2; Sick s2(2); }
The launch above will display:
double 2 int 2
Shows that two apparently equivalent initializations actually select different constructors.
(Or like the Truncheon mentioned in the question, and I missed that the explicit keyword should be in the Sick(double d) constructor).
Michael burr
source share