Java wildcards... in D

Voitech via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jan 18 14:08:20 PST 2016


On Monday, 18 January 2016 at 21:15:51 UTC, Chris Wright wrote:
> On Mon, 18 Jan 2016 19:19:22 +0000, Voitech wrote:
>
>> Hi. I'm trying to parse an simple string expression to 
>> something like Element array. Each Element can have a value of 
>> unknown type, which will be further combined and calculated to 
>> let say real/double/float value, no mather.
>
> In Java, Element<T> is always Element<Object> behind the 
> scenes, and there's only one type.
>
> In D, Element(T) is a template that produces a type. 
> Element!int and Element!Object are entirely different and, 
> thanks to what templates allow you to do, the compiler can't 
> assume any relationship between the two.
>
> You have to establish that relationship manually by creating a 
> base type:
>
> abstract class BaseElement {
> }
>
> class Element(T) : BaseElement {
>   T value;
> }
>
> Alternatively, if this is not appropriate to your usecase, you 
> may want to look at std.variant, which explicitly implements 
> value boxing.

Thank you for answering. I think i will use std.variant.Algebraic 
implementation for my needs. But about Algebraic... why first 
template parameter of it must be always int. Let say i want to 
store only real and string in Algebraic no int.
if i try to do something like :

alias Element =Algebraic!(real,string);

i will get:

Cannot store a int in a VariantN!(16LU, real, string)

if i declare as:

alias Element =Algebraic!(int,real,string);

this will be ok.

But anything other than Algebraic!(int,x,y,z...) doesn't compile, 
like:

alias Element =Algebraic!(uint,bool,string); //compilation error
alias Element =Algebraic!(ulong,Object,bool); //compilation error
alias Element =Algebraic!(long,real,string); //compilation error

Why is that ?


Cheers Voitech.


More information about the Digitalmars-d-learn mailing list