`examplevalues` property
Andrea Fontana via Digitalmars-d
digitalmars-d at puremagic.com
Mon Aug 3 07:30:42 PDT 2015
On Monday, 3 August 2015 at 13:54:51 UTC, HaraldZealot wrote:
> On Monday, 3 August 2015 at 13:13:55 UTC, Andrea Fontana wrote:
>>
>> Why don't you use templates? Something like:
>>
>> enum ValueType
>> {
>> Init,
>> Min,
>> Max
>> }
>>
>> auto exampleValues(T)()
>> {
>> T[ValueType] retVal;
>>
>> retVal[ValueType.Init] = T.init;
>> static if (__traits(compiles, T.min)) retVal[ValueType.Min] =
>> T.min;
>> static if (__traits(compiles, T.max)) retVal[ValueType.Max] =
>> T.max;
>>
>> return retVal;
>> }
>>
>> exampleValues!int.writeln;
>> exampleValues!string.writeln;
>
> Good solution!
>
> But there is something that not perfect: it can be customizable
> only with template specialization as I see. I want not only
> standard values like `init` `max` or `min` but also some
> example value like 1, 2, 3, 4, 5 for `int`. In last case your
> template solution not so convenient as desired (introduction in
> language feature like `.testValue1` seems ridiculous, and
> without that only template specialization can provide
> customization, as I have said).
>
> But this seems interesting direction, and easy to implement in
> object.d (without library implementation, this feature have
> little benefit).
You have to write the same amount of code.
It's just one line for each type... Something like:
import std.traits;
enum ValueType
{
Init,
Min,
Max
}
auto exampleValues(T)()
{
T[ValueType] retVal;
retVal[ValueType.Init] = T.init;
static if (__traits(compiles, T.min)) retVal[ValueType.Min] =
T.min;
static if (__traits(compiles, T.max)) retVal[ValueType.Max] =
T.max;
static if(isIntegral!T) return tuple!("defaults",
"customs")(retVal, [1,2,3,4,5]);
else static if(isFloatingPoint!T) return tuple!("defaults",
"customs")(retVal, [1.0,2.0,T.nan]);
else static if(isSomeString!T) return tuple!("defaults",
"customs")(retVal, ["hello", "world"]);
else return tuple!("defaults", "customs")(retVal, T[].init);
}
More information about the Digitalmars-d
mailing list