Reputation: 13
As part of my code's logic, I'm assigning the result of an expression involving mpz_class to an int. The problem is, mpz_class overloaded operators don't seem to produce mpz_class objects, but rather, some kind of temporaty object that then gets converted to mpz_class (if I understood this correctly). Because of this Is there any way that I can convert the result of bignum % 10 to an int inline?
int digit_sum = 0;
while(bignum > 0) {
digit_sum += bignum % 10;
bignum /= 10;
}
Upvotes: 1
Views: 244
Reputation: 20569
The GMP library uses expression templates to avoid unnecessary temporary variables. As such, bignum % 10
returns a proxy that represents the expression and only evaluates when converted to mpz_class
. Also, mpz_class
does not implicitly convert to int
. Therefore, as mentioned in comment, you need to first convert to mpz_class
and then use the get_si
method to convert the mpz_class
to long
.
digit_sum += mpz_class{bignum % 10}.get_si();
Note that in general, you need to make sure that the number actually fits into long
before calling get_si
. In this case, the (absolute) number is always less than 10, so it is safe to call get_si
.
Upvotes: 1