Choosing between mpf_class and double at compile time

Décio Luiz Gazzoni Filho decio at decpp.net
Thu Feb 26 15:39:11 CET 2009


On Feb 26, 2009, at 7:25 AM, Pasquale Tricarico wrote:

> Hi,
>
> This is my first post, but I have been using GMP for more than 5
> years. I have a fair size C++ project that makes heavy use of
> mpf_class, and for performance and testing reasons I would like to
> have the possibility to switch between mpf_class and plain double at
> compile time. In my code I have:
>
> typedef mpf_class Double;
>
> and then I always refer to Double in my code. This works really well,
> but now if I want to switch to double, replacing the above typedef
> with the following one is not enough of course:
>
> typedef double Double;
>
> This doesn't work because of all the methods I already call in the
> code, such as Double::get_mpf_t(), conversions from/to mpz_class,
> printing using gmp_printf("%Ff..."), and probably for a few more
> reasons I haven't bumped into yet. Subclassing from double is not
> possible as double is not a C++ class but just a type. One approach
> could be to fill the code with macro switches such as:
>
> #ifdef USE_GMP
>   gmp_printf("%Ff",x.get_mpf_t());
> #else
>   printf("%f",x);
> #endif
>
> But this would severely degrade the code. So I was wondering if anyone
> here on the list has a good solution to switch between mpf_class and
> double the smart way, staying away from evil macros. Thanks a lot.

This probably wouldn't be very efficient, but you could declare a  
class like:

template<class T> class Double_t
{
	T t;

	/* ... */
}

Inside you could define any operators and utility functions you might  
want, then use partial template specialization to implement the parts  
that are different between double and mpf_class. Then use a typedef  
Double_t<mpf_class> Double; or typedef Double_t<double> Double; as  
desired.

A simpler solution would be to have overloaded functions for each use  
of mpf_class or double, e.g.

void print_number(double number);
void print_number(mpf_class number);

Décio


More information about the gmp-discuss mailing list