Node:C++ Interface General, Next:, Previous:C++ Class Interface, Up:C++ Class Interface



C++ Interface General

All the C++ classes and functions are available with

#include <gmpxx.h>

The classes defined are

mpz_class Class
mpq_class Class
mpf_class Class

The standard operators and various standard functions are overloaded to allow arithmetic with these classes. For example,

int
main (void)
{
  mpz_class a, b, c;

  a = 1234;
  b = "-5678";
  c = a+b;
  cout << "sum is " << c << "\n";
  cout << "absolute value is " << abs(c) << "\n";

  return 0;
}

An important feature of the implementation is that an expression like a=b+c results in a single call to the corresponding mpz_add, without using a temporary for the b+c part. Expressions which by their nature imply intermediate values, like a=b*c+d*e, still use temporaries though.

The classes can be freely intermixed in expressions, as can the classes and the standard types long, unsigned long and double. Smaller types like int or float can also be intermixed, since C++ will promote them.

Note that bool is not accepted directly, but must be explicitly cast to an int first. This is because C++ will automatically convert any pointer to a bool, so if GMP accepted bool it would make all sorts of invalid class and pointer combinations compile but almost certainly not do anything sensible.

Conversions back from the classes to standard C++ types aren't done automatically, instead member functions like get_si are provided (see the following sections for details).

Also there are no automatic conversions from the classes to the corresponding GMP C types, instead a reference to the underlying C object can be obtained with the following functions,

mpz_t mpz_class::get_mpz_t () Function
mpq_t mpq_class::get_mpq_t () Function
mpf_t mpf_class::get_mpf_t () Function

These can be used to call a C function which doesn't have a C++ class interface. For example to set a to the GCD of b and c,

mpz_class a, b, c;
...
mpz_gcd (a.get_mpz_t(), b.get_mpz_t(), c.get_mpz_t());

In the other direction, a class can be initialized from the corresponding GMP C type, or assigned to if an explicit constructor is used. In both cases this makes a copy of the value, it doesn't create any sort of association. For example,

mpz_t z;
// ... init and calculate z ...
mpz_class x(z);
mpz_class y;
y = mpz_class (z);

There are no namespace setups in gmpxx.h, all types and functions are simply put into the global namespace. This is what gmp.h has done in the past, and continues to do for compatibility. The extras provided by gmpxx.h follow GMP naming conventions and are unlikely to clash with anything.