Why are invalid conversion functions weird?

Why the next program

#include <iostream> struct C { operator int() { std::cout << "C::operator int()" << std::endl; return 0; } operator void() { std::cout << "C::operator void()" << std::endl; } }; int main() { C c; (int)c; (void)c; // this does run the function: // c.operator void(); } 

bring it out

 C::operator int() 

instead of this?

 C::operator int() C::operator void() 

Live demo at coliru.

The immediate answer, as always, is because the standard says so.

C ++ 11 Standard, Β§ 12.3.2

The conversion function is never used to convert a (possibly cv-qualified) object for (possibly cv-qualified) the same type of object (or a reference to it), to the base class (possibly cv-qualit) this type (or reference to him) or (possibly cv-qualified) void.

So why does the standard say so? What is the use of using void conversion functions in a particular case?

Additional exposure in footnote 116:

These transformations are considered standard transformations for the purpose of overload resolution (13.3.3.1, 13.3.3.1.4) and, therefore, initialization (8.5) and explicit casts (5.2.9). Converting to void does not cause any conversion function (5.2.9). Although never directly called to perform the conversion, such conversion functions can be declared and can potentially be achieved by invoking a virtual conversion in the base class.

I just used (void) to disable compiler warnings about unused variables. It seems like others are using it too.

Why use unused return values ​​for void?

If the void conversion functions were performed according to the typical rules of the conversion functions, this could allow surprises, but this is true for any conversion function with side effects and creating these surprises, it would be at the discretion of the programmer.

+8
c ++ language-lawyer type-conversion c ++ 11
source share

No one has answered this question yet.

See similar questions:

93
Why use unused return values ​​for void?
33
Why is the "void statement" not called with cast syntax?
3
(void) r ++ iterator input requirement

or similar:

23498
Why is processing a sorted array faster than processing an unsorted array?
2437
Why "use the std namespace;" considered bad practice?
2116
Why are stigment additions much faster in individual cycles than in a combined cycle?
1675
Why is reading strings from stdin much slower in C ++ than Python?
1643
Why can templates be implemented only in the header file?
1483
Why should I use the pointer and not the object itself?
1138
Why do we need virtual functions in C ++?
4
Why does the C ++ standard require compilers to ignore calls to conversion operators for base types?
3
Explicit conversion functions, direct initialization, and constructor conversion
0
Accessing private values ​​in cpp using pointers

All Articles