Implicit cast of int to a class

Bill Baxter dnewsgroup at billbaxter.com
Sun Nov 4 10:22:40 PST 2007


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?

> 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


More information about the Digitalmars-d-learn mailing list