Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast instance to void?

Tags:

c++

casting

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();
}
  • Why is A not allowed? (if I would replace void with int it would obviously work)
  • Why does neither B nor C call my conversion operator? (again, if I replaced void by int all three versions would call my operator int).
  • I could accept that this is the way casting to void works, but then why am I allowed to define an operator void when it isnt used as I would expect?
like image 536
463035818_is_not_a_number Avatar asked Sep 11 '25 14:09

463035818_is_not_a_number


1 Answers

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.

like image 82
Kerrek SB Avatar answered Sep 14 '25 05:09

Kerrek SB