The C++ interface implicitly converts rationals to integers

Roberto Bagnara bagnara at cs.unipr.it
Fri Nov 18 22:49:49 CET 2005


Hi there.

The program

#include <gmpxx.h>
#include <iostream>

using namespace std;

void foo(const mpz_class& i) {
   cout << "foo::i = " << i << endl;
}

int main() {
   mpq_class r(3, 4);
   cout << "main::r = " << r << endl;
   foo(r);
   return 0;
}

prints

main::r = 3/4
foo::i = 0

This shows that the C++ interface of GMP defines an implicit constructor
for mpz_class that takes an mpq_class object and (silently) truncates it.
It is very bad practice for such a constructor to be implicit as this can
result in bugs that are very difficult to diagnose.  Of course I am not
questioning the need for such a conversion: I simply think that truncation
should only be performed when explicitly requested.
All the best,

    Roberto

-- 
Prof. Roberto Bagnara
Computer Science Group
Department of Mathematics, University of Parma, Italy
http://www.cs.unipr.it/~bagnara/
mailto:bagnara at cs.unipr.it


More information about the gmp-discuss mailing list