Is it possible to override (C-style) casts in C++?
Suppose I have the code
double x = 42;
int k = (int)x;
Can I make the cast in the second line execute some code I wrote? Something like
// I don't know C++
// I have no idea if this has more syntax errors than words
operator (int)(double) {
std::cout << "casting from double to int" << std::endl;
}
The reason I ask is because of the question “Is there any way to get gcc or clang to warn on explicit casts?” and my suggestion there.
Yes, we can make conversions, but only if one or both sides is a user-defined type, so we can’t make one for
doubletoint.As Robᵩ pointed out, you can add the
explicitkeyword to either of those conversion functions, which requires the user to explicitly cast them with a(demostruct)argcor(int)dslike in your code, instead of having them implicitly convert. If you convert to and from the same type, it’s usually best to have one or both asexplicit, otherwise you might get compilation errors.