结合 GMPXX 和 C++11 及更高版本
Combining GMPXX and C++11 and later
我在结合 GMP 和 C++11 时遇到了一个小问题。
示例程序:
#include <gmpxx.h>
int main()
{
mpz_class a,b; //ok
auto c = a+b; //ok (?)
c = 0; //error
}
错误信息:
error: no match for 'operator=' (operand types are '__gmp_expr<__mpz_struct [1], __gmp_binary_expr<__gmp_expr<__mpz_struct [1], __mpz_struct [1]>, __gmp_expr<__mpz_struct [1], __mpz_struct [1]>, __gmp_binary_plus> >' and 'int')
c = 0;
^
有什么问题?
原因是 operator+(mpz_class const&, mpz_class const&)
不是 return 另一个 mpz_class
,而是一个中间结果类型 __gmp_expr<T, U>
.
中有评论
Results of operators and functions are instances of __gmp_expr<T, U>
.
...
Actual evaluation of a __gmp_expr<T, U>
object is done when it gets
assigned to an mp*_class
("lazy" evaluation): this is done by calling
its eval() method.
当您使用 auto c = a + b;
时,您会得到 c
属于 __gmp_expr<T, U>
类型,因此其他 mp*_class
或整数无法分配给它。
我在结合 GMP 和 C++11 时遇到了一个小问题。
示例程序:
#include <gmpxx.h>
int main()
{
mpz_class a,b; //ok
auto c = a+b; //ok (?)
c = 0; //error
}
错误信息:
error: no match for 'operator=' (operand types are '__gmp_expr<__mpz_struct [1], __gmp_binary_expr<__gmp_expr<__mpz_struct [1], __mpz_struct [1]>, __gmp_expr<__mpz_struct [1], __mpz_struct [1]>, __gmp_binary_plus> >' and 'int')
c = 0;
^
有什么问题?
原因是 operator+(mpz_class const&, mpz_class const&)
不是 return 另一个 mpz_class
,而是一个中间结果类型 __gmp_expr<T, U>
.
Results of operators and functions are instances of
__gmp_expr<T, U>
....
Actual evaluation of a
__gmp_expr<T, U>
object is done when it gets assigned to anmp*_class
("lazy" evaluation): this is done by calling its eval() method.
当您使用 auto c = a + b;
时,您会得到 c
属于 __gmp_expr<T, U>
类型,因此其他 mp*_class
或整数无法分配给它。