Because int is implicitly constructible and assignable from a double, complete with the loss of precision. I'm sure the same is true in plain C. Annoying, yes, but that's the cost of backward compatibility. I was about to suggest using BOOST_STRONG_TYPEDEF, but the implicit conversion from double to int prevents that from helping. I think you could using the same idea as BOOST_STRONG_TYPEDEF but provide a private constructor for double and for float to prevent it from constructing an int when you try to construct with a non-integral constant.
Don't get me wrong; I completely agree that implicit type conversion is evil. That's an ugly hack to replace some evil with different evil. I'd be happy to break C compatibility for a little safety like this.
There is no good reason why it doesn't issue a warning. We have warnings for unused variables, even though they're technically allowed in both C and C++, so any argument about backwards compatibility doesn't hold water for me. I feel there should be a similar warning for dumb casts like this.
The bigger issue, really, is that C made a bunch of goofy design mistakes, and so we've expended a great deal of effort being backwards-compatible with things that we shouldn't have done in the first place.
Like implicit type conversion, and comments that still won't nest. (Yes, I know why C's comments don't nest, but that's a stupid reason these days)
I think the real underlying problem is that people continue to write in C++. We're still using a language invented in the early '80s based off a language written in the early '70s. I can't blame C or C++ for not incorporating lots of modern ideas into their design, because those ideas weren't around back then. I can, however, blame people who cling to C/C++ simply because that's the way they've always done things. Sure, C/C++ have the advantage that there's already a lot of stuff written for them so you've got lots of libraries that you don't need to implement yourself. but that excuse should have gone away when Java and Python grew up into the languages we know today.
Comments 9
Yea, like this:
#include
struct safe_int
: boost::totally_ordered1< safe_int
, boost::totally_ordered2< safe_int ( ... )
Reply
I claim (without proof) that implicit type conversion is always a Bad Idea. Languages with modern type systems agree with me.
Reply
Not that we've ever expected C++ to keep us from doing goofy things, of course.
Reply
Reply
Reply
Like implicit type conversion, and comments that still won't nest. (Yes, I know why C's comments don't nest, but that's a stupid reason these days)
Reply
Reply
Leave a comment