c++castingvoid

Cast instance to void?


This question is probably of little practial value, but I am just trying to understand what is going on here. I have a class:

#include <iostream>
struct Foo{
     operator void () { 
         std::cout << " to void called " << std::endl;
         return;
     }
};

Actually I wasnt sure if it is possible to convert a type to void (still not sure if it makes any sense, though), but after reading this question I learned that it is possible at least via static_cast.

Now my question is....

void foo() {
    Foo f;
    //return f;                     // A // not allowed
    return static_cast<void>(f);    // B // OK
    return (void) f;                // C // OK
}
int main() {
    foo();
}

Solution

  • The "cast to void", however it is spelled, is a discarded value expression. It does not constitute a conversion, and therefore does not consider conversion functions.

    C++ allows you to do lots of things that are pointless; it would be harder to forbid some special cases than to just leave the rules general.