Search code examples
c++implicit-conversionarithmetic-expressions

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
// ...

Solution

  • 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: