Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inhibit implicit conversion while using arithmetic operators

How can we tell the C++ compiler that it should avoid implicit casting while using arithmetic operators such as +and /, i.e.,

size_t st_1, st_2;
int    i_1,  i_2;

auto st = st_1 + st_2; // should compile
auto i  = i_1  + i_2;  // should compile

auto error_1 = st_1 + i_2;  // should not compile
auto error_2 = i_1  + st_2; // should not compile
// ...
like image 773
abraham_hilbert Avatar asked Mar 10 '23 17:03

abraham_hilbert


1 Answers

Unfortunately the language specifies what should happen when you add an int to a size_t (see its rules for type promotion) so you can't force a compile time error.

But you could build your own add function to force the arguments to be the same type:

template <class Y>
Y add(const Y& arg1, const Y& arg2)
{
    return arg1 + arg2;
}

The constant references prevent any type conversion, and the template forces both arguments to be the same type.

This will always work in your particular case since size_t must be an unsigned type:

like image 145
Bathsheba Avatar answered Apr 27 '23 00:04

Bathsheba