Implicit cast of int to a class

Matthias Walter walter at mail.math.uni-magdeburg.de
Sun Nov 4 12:29:14 PST 2007


Bill Baxter Wrote:

> Matthias Walter wrote:
> > 
> > Okay, I found one solution for everything which at least works:
> > 
> > a function num (T) (int n), which returns n if T is a native integer or "new T (n)" if not.
> > This work's as follows:
> > 
> > | void func (T) (T input = num !(T) (0))
> > | {
> > |   // ...
> > | }
> > |
> > | T a = num !(T) (1); // is correctly initialized.
> > |
> > | func !(T) (); // works with default parameter 0
> > | func !(T) (num !(T) (2)); // works
> > 
> > This is ugly typing (at least for a library like GMP, where one likes to do things like with normal integers!), 
> 
> If you want things to behave like normal integers, then you really 
> should be using a struct instead of a class.  The class reference 
> semantics mean that assignment will always act very unlike a normal 
> integer.  Is there some reason you can't make it a struct?  Do you need 
> inheritance?

Yes, indeed, there is a good reason: If you work with references, the use of temporaries is not a slowdown, because copying a reference is really cheap. If I'd use structs and thus call-by-value, there would be a real temporary for simple things like:

a = b + c;

To avoid this creation of temporaries, one has to make heavy use of templates like the GMP guys did for the C++ headers. (They encoded the expression type in the template type and resolved everything, including assignment operations via templates to achieve a minimal number of temporaries) They did this for all basic stuff and some functions like abs, cmp, etc.
Currently, I only have my mpz_class, which, written in a straightforward way, already has 2k lines due to all those possible functions and operator combinations and unittests. With the template approach, I guess this would be increased by a factor of 4, making the code really unmaintainable. (If you like, you can inspect your personal /usr/include/gmpxx.h :) )
Additionally, some ideas from Ben Hinkle (Recycling of GMP variables to avoid allocations) cannot be easily implemented with the template implementation.
Last but not least, I don't know, whether the template approach can be done in D at all - e.g. operators must belong to a class, which is not the case in GMP C++ headers, so I don't know, if this problem is feasible.

Any ideas, how to handle this problem?

> 
> > so the problem could be solved, if
> > 
> > int i = new int (1);
> > 
> > would be semantically equivalent to
> > 
> > int i = 1;
> 
> Probably not going to happen.  But I could maybe see Walter making 
> initializers like that call this(int).  In fact for structs I think 
> something like that already tries to call static opCall(int) if it 
> exists.  Maybe that works for classes too?
> 
> --bb

I'm going to check this out, thanks!

Matthias Walter


More information about the Digitalmars-d-learn mailing list