Nullable instantiator anyone?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 17 18:21:59 PDT 2014


On 08/17/2014 12:05 PM, "Nordlöw" wrote:

 > On Sunday, 17 August 2014 at 18:51:38 UTC, bearophile wrote:
 >> It could be sufficient, but note that in Phobos there are two
 >> different versions of Nullable, one of them doesn't require extra
 >> memory, it uses one value as the "null" value.
 >
 > Ok, thanks for the reminder.
 >
 > Do you have a suggestion of an instantiator for this variant? I'm not
 > sure how to define this. So far I have
 >
 >
 > Nullable!T nullable(T nullValue, T)(T a, T nullValue)
 > {
 >      return Nullable!nullValue(a);
 > }
 >
 > unittest
 > {
 >      auto x = nullable!(int.max)(3);
 > }
 >
 >
 > but it fails as
 >
 >
 > mangling.d(50,21): Error: undefined identifier T
 >
 >
 > How do I make the template parameter nullValue infer type T with a
 > single template parameter? Is it even possible?

I don't think it is possible.

The following solution relies on an alias template parameter and a 
template constraint. The code covers both Nullable variants:

import std.typecons;

auto nullable(T)(T value)
{
     return Nullable!T(value);
}

unittest
{
     auto x = nullable(42.5);
     assert(is(typeof(x) == Nullable!double));
}

auto nullable(alias nullValue, T)(T value)
     if (is (typeof(nullValue) == T))
{
     return Nullable!(T, nullValue)(value);
}

unittest
{
     auto x = nullable!(int.max)(3);
     assert(is (typeof(x) == Nullable!(int, int.max)));
}

void main()
{}

Ali



More information about the Digitalmars-d-learn mailing list