TypeFunction example creatiing a conversion matrix

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Oct 1 18:19:57 UTC 2020


On Thu, Oct 01, 2020 at 05:55:17PM +0000, Stefan Koch via Digitalmars-d wrote:
[...]
> Please show me in the code where is(T : U) is used.
> I don't find it in std variant.

That's because it doesn't work.

We would like to be able to do this:

	Variant v;
	v = 100; // v now stores an int
	long l = v.get!long; // currently does not work

We cannot do this because the type of 100 is not known by Variant until
runtime, and at runtime, we cannot tell whether the stored type (int) is
implicitly convertible to the requested type (long).  So, we cannot
perform the implicit conversion.

This limitation makes Variant very unfriendly to use: unless you know
precisely what type is stored, you cannot get anything useful out of it.
If somebody stored an int in a Variant and hands it to you, and you want
a long (after all, the language supports implicit conversion from int to
long), you cannot get a long out of it without knowing beforehand it was
an int. In practice, this means lots of code duplication: if v.get!long
throws, try v.get!int; if that still doesn't do it, try v.get!short;
etc.. Basically you end up duplicating implicit conversions that the
compiler should have done for you.

We would like Variant to behave like a top type, but we can't because we
cannot duplicate the implicit conversions of stored types. We can get
most of the way there, but not all the way.


T

-- 
"Maybe" is a strange word.  When mom or dad says it it means "yes", but when my big brothers say it it means "no"! -- PJ jr.


More information about the Digitalmars-d mailing list