std.sumtype?

Paul Backus snarwin at gmail.com
Mon Mar 22 23:25:07 UTC 2021


On Monday, 22 March 2021 at 22:03:07 UTC, jmh530 wrote:
> On Monday, 22 March 2021 at 21:43:58 UTC, Paul Backus wrote:
>> On Monday, 22 March 2021 at 19:24:54 UTC, JN wrote:
>>> Does anyone know if it would be possible to make it support 
>>> (it doesn't support it now) this kind of syntax:
>>>
>>> Temperature t1 = Fahrenheit(98.6);
>>> isFahrenheit(t1); // works
>>> isFahrenheit(Fahrenheit(98.6)); // doesn't work :(
>>
>> You can do this by adding an additional overload to 
>> isFahrenheit:
>>
>> bool isFahrenheit(T)(T t)
>>     if (staticIndexOf!(T, Temperature.Types) >= 0)
>> {
>>     return is(T == Fahrenheit);
>> }
>>
>> bool isFahrenheit(Temperature temp)
>> {
>>     // Forward to template overload
>>     return temp.match!isFahrenheit;
>> }
>
> What about something like
> Fahrenheit t2 = t1.to!(BaseTypeOf!(typeof(t1)));
> that could then be put into its own function.

Not sure what `BaseTypeOf` is supposed to do here, but if you 
want to extract a particular type from a SumType it's pretty easy:

Target to(Target, Source)(Source source)
     if (isSumType!Source && staticIndexOf!(Target, Source.Types) 
 >= 0)
{
     // Will throw MatchException if the wrong type is found
     return source.tryMatch!((Target target) => target));
}


More information about the Digitalmars-d mailing list