Michael
Michael

Reputation: 5897

Forbidding implicit `unsigned` to `double` conversion

Is it possible to forbid implicit conversion between basic types in C++? In particular, I'd like to forbid implicit conversion from unsigned to float or double because of bugs like these:

int i = -5;
...
unsigned u = i; // The dawn of the trouble.
...
double d = u;   // The epicenter of the bug that took a day to fix.

I tried something like this:

explicit operator double( unsigned );

Unfortunately, that didn't work:

explicit.cpp:1: error: only declarations of constructors can be ‘explicit’
explicit.cpp:1: error: ‘operator double(unsigned int)’ must be a nonstatic member function

Upvotes: 2

Views: 108

Answers (1)

Brian Bi
Brian Bi

Reputation: 119174

You can't simply remove an implicit standard conversion from the language altogether.

Having said that, there are ways to prevent undesired conversions in some situations. During initialization, you can prevent narrowing conversions by using brace syntax. A conversion between floating and integral types is always considered narrowing (edit: except when the source is an integer constant expression).

int i {-5};       // ok; -5 fits in an int
unsigned u = i;   // ok; no check for narrowing using old syntax
double d {u};     // error: narrowing

If you are writing a function that takes a double, you can prevent passing an integral type by adding overloads for integral types, then deleting them.

Upvotes: 5

Related Questions