Dear C++

Feb 23, 2009 17:58

Dear C++:

When I type

const int THRESHOLD = 0.5;

and compile it with -Wall, why do you not complain?

Leave a comment

benfrantzdale February 24 2009, 02:00:47 UTC
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.

Yea, like this:

#include

struct safe_int
: boost::totally_ordered1< safe_int
, boost::totally_ordered2< safe_int ( ... )

Reply

macdaddyfrosh February 24 2009, 02:03:25 UTC
That's egregious.

I claim (without proof) that implicit type conversion is always a Bad Idea. Languages with modern type systems agree with me.

Reply

macdaddyfrosh February 24 2009, 02:04:55 UTC
From a less-crotchety perspective, it seems like this should at least issue a compiler warning, as it's clearly a goofy thing to do.

Not that we've ever expected C++ to keep us from doing goofy things, of course.

Reply

benfrantzdale February 24 2009, 02:16:16 UTC
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.

Reply

macdaddyfrosh February 24 2009, 02:17:02 UTC
I had a hell of a time trying to convince my office that implicit type conversion is a bad thing. I'm glad somebody agrees! :-D

Reply

aposiopetic February 24 2009, 03:09:49 UTC
You sir, have these things called "principles". I surmise that your office believes implicitly converting to these sorts of things is evil, or at best an ugly hack. =P

Reply


Leave a comment

Up