TypeFunction example creatiing a conversion matrix

Steven Schveighoffer schveiguy at gmail.com
Thu Oct 1 18:40:32 UTC 2020


On 10/1/20 2:26 PM, H. S. Teoh wrote:
> On Thu, Oct 01, 2020 at 02:08:11PM -0400, Steven Schveighoffer via Digitalmars-d wrote:
>> On 10/1/20 1:35 PM, Andrei Alexandrescu wrote:
> [...]
>>> How do you implement Variant.get(T) without reifying is(T : U)?
>>
>> How do you implement Variant.get(T) *with* reifying is(U : T)?
>>
>> step 1: determine using reified constructs that U is convertible to T
>> step 2: ?????
>> step 3: Return a T from a U!
>>
>> BTW, Variant already does a *limited* form of this. reification
>> doesn't change what needs to happen.
>>
>> I don't see why Variant's needs have to dictate how you need to reason
>> about types at compile time in CTFE.
> [...]
> 
> I think what Andrei is getting at is, we want to be able to transfer the
> compiler's knowledge and implementation of implicit type conversions to
> runtime.  I.e., we'd like to do this:
> 
> 	Variant v;
> 	v = 100;	// v now stores an int
> 	...
> 	long l = v.get!long; // currently doesn't work

Again, this does work, but I don't think this completely destroys your 
point.

> Or maybe, a more motivating example:
> 
> 	T calculate(T)(Variant number) {
> 		T val = number.get!T;
> 		return val*2 + 1;
> 	}
> 
> 	Variant v;
> 	v = 100;
> 	assert(calculate!long(v) == 201L);
> 	assert(calculate!float(v) == 201.0f);

This currently works as well.

There *are* cases that don't work. But that's a matter of fixing 
ImplicitlyConversionTargets.

> 
> I.e., you don't know what type you'd like to get from the Variant until
> the caller calls you, but you also don't know what type is stored in
> Variant until runtime.  Currently, there's a hack in Variant to handle
> some of these implicit conversions, but as Andrei says, it's incomplete
> and may have some wrong cases.  This knowledge is already in the
> compiler; there should be a way to transfer this to Variant at runtime
> without having to re-implement implicit conversions in library code.

That's all fine. The problem I see is:

1. Variant (a true variant that can hold ANY type) is really the only 
use case for runtime type information. Like, literally the only. 
Algebraic types don't have to use reification *at all*. Any reification 
system is still not going to encompass all you can do with a type. Sure, 
you can probably 100% cover type conversion. It will never 100% cover, 
e.g. comparison or type coersion.
2. Compile time is the main focus here. Variant works, and can be made 
better, and we don't have to introduce a new concept to make it work. 
But in CTFE, pulling back the Oz curtain a bit can make things an insane 
amount more pleasant. We don't need to reimplement what the compiler 
does at runtime for this.

-Steve


More information about the Digitalmars-d mailing list