简体   繁体   中英

Casting an mpz_class temporary to int

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;
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM