Implicit cast of int to a class

torhu no at spam.invalid
Sat Nov 3 17:42:33 PDT 2007


Matthias Walter wrote:
> Hello,
> 
> I have a class called mpz_class which in particular implements the following:
> 
> 1. this (int other) { ... }
> 2. opAssign (int other) { ... }
> 
> I now want to write templated code with T = int, T = long and T = mpz_class.
> My mpz_class should work and feel like the orginal integers, which mostly works.
> 
> I'd like to know, how I can coax my class to implicitely convert integer literals to instances of it. There are 2 cases which don't compile for me and one which is semantically wrong:
> 
> // 1.
> void func (T) (T input = 0) // error:  cannot implicitly convert expression (0) of type int to gmp.mpz.mpz_class

I don't think it's possible to use defaults args like this.  It seems 
that opAssign isn't used for default args.  You need to remove the 
default, overload the function, specialize the template, or redesign the 
whole thing.


> // 2. 
> T a = 1; // I guess, a points to 0x1 now and not to a result of mpz_class.this(1)

Even if it tried to call opAssign, there's no object allocated.  It 
would just crash.  You have to use 'new' somewhere.  Maybe it's better 
to use a struct with static opCall overloads, instead of a class?  A 
struct is a better fit if you want it to behave like ints and longs, for 
sure.

Mixing built-in types with user-defined types in D needs to be more 
explicit than in C++, because there are no implicit conversions.  Except 
for the very limited opAssign.

One option is to find a single point in your code where you can convert 
ints and longs to mpz_class, and then the rest of the code uses that.

Of course, if all you want is to make code that can work with both ints 
and longs, things would probably be a lot simpler.  But I guess you're 
just trying out stuff?

Your design seems a bit too complex for its own good, although I'm not 
sure what you're trying to achieve. :)


More information about the Digitalmars-d-learn mailing list