SafeInt strategy for implicit cast to larger type

Mar 2, 2016 at 5:48 AM
Consider this example code:
#include <iostream>
#include <limits>
#include <SafeInt3.hpp>

int main()
    SafeInt<unsigned int> ui = std::numeric_limits<unsigned int>::max();
    unsigned long long int ulli = 10;
    unsigned long long int result = ui + ulli;
    std::cout << result << std::endl;;
    return 0;
SafeInt raises an exception during operator+. Is there a reason why? It seems to me there is no way this can be unsafe, and thus SafeInt should allow it. Using a native unsigned int instead of a SafeInt<unsigned int>, the compiler would implicitly cast ui to an unsigned long long, and perform a valid addition, yes?

Just wondering what I am missing...

Mar 18, 2016 at 3:52 PM
SafeInt has an operator + overload. The following overload is called in the case above. As you can see the return type of the operation is SafeInt<T, E> where T is same type as the input SafeInt. So in your case it is SafeInt<unsiged int> which cannot fit the result.
template < typename T, typename U, typename E >                                 
SafeInt< T, E > operator +( U lhs, SafeInt< T, E > rhs ) SAFEINT_CPP_THROW      
    T ret( 0 );                                                                 
    AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( (T)rhs, lhs, ret );
    return SafeInt< T, E >( ret );