Specify an instance of an instance?
This question is probably not very practical, but I'm just trying to figure out what's going on here. I have a class:
#include <iostream>
struct Foo{
operator void () {
std::cout << " to void called " << std::endl;
return;
}
};
Actually I wasn't sure if it was possible to convert the type to void
(still not sure if it makes any sense), but after reading this question I found out that it is possible, at least through 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 replaced
void
withint
, it obviously worked) - Why don't B or C call my conversion operator? (again, if I replaced
void
withint
, all three versions would call mineoperator int
). - I could agree that this works when in use
void
, but why can I detectoperator void
when it is not in use as I would expect?
+3
source to share
1 answer
"cast to void", however it is written, is the cast value of the expression. It is not a transformation and therefore does not consider transformation functions.
C ++ lets you do a lot of things that don't make sense; it would be more difficult to prohibit some special cases than just leave the general rules.
+4
source to share