It seems that, like in new standards, you can use the keyword explicit not only to constructors to prevent implicit coercion, but also to operators. Can you explain why this is necessary and give an example? Perhaps there are other uses?

    1 answer 1

    explicit for transformation operators is needed for the same reason as for constructors. Requiring a programmer to explicitly specify the type in order to avoid unexpected code behavior when implicitly casting.

    The most popular example is the operator bool . Prior to c ++ 11, the lack of the ability to specify explicit for the type-conversion operator required a rather unobvious scheme for implementing the Safe Bool idiom. Those. use of an object of our type in context when coercion to a boolean type is required, for example, inside an if or while . In particular, you can pay attention to std::ios::operator bool . The link clearly shows the difference between c ++ 98 and c ++ 11.

    The fact that previously it was impossible to set "explicitness" for the transformation operator in essence is an annoying flaw, since the conversion operator and the constructor with one parameter (for which explicit just relevant) are essentially meant for the same thing. The only difference is from which side to look. If we create a class N , then a constructor of the form N(O o) will convert type O to type N For conversion in the opposite direction, either a constructor of the form O(N n) needed (but this is sometimes impossible, since the type O can be closed or not be a class at all), or operator O(N n) .