January 20, 2014 Generic Span/Limits/MinMax Type | ||||
---|---|---|---|---|
| ||||
Has anyone cooked up a generic D struct that groups together min and max values of a type and default-initializes them in the correct way? Something like struct Limits(T) { /* TODO: Fix purity of this by fixing Bytes.value() */ auto init() @trusted /* pure */ nothrow { return tuple(T.max, T.min); } alias _minmax this; Tuple!(T,T) _minmax; } auto limits(T)() { return Limits!T(); } unittest { Limits!int x; dln(x); } I want min and max to default initialize to T.max, T.min so they are prepared for x = min/max(x, ...) arithmetic. But the code above doesn't work because the init() function isn't called and I don't know why. And I can't use default member initialization because I want `Limits` to work also with types such as `SysTime` when min and max are only know at run-time. I'm aware of `std.datetime.span` but it isn't generic. Ideas anyone? |
January 20, 2014 Re: Generic Span/Limits/MinMax Type | ||||
---|---|---|---|---|
| ||||
Posted in reply to Nordlöw | On Monday, 20 January 2014 at 19:36:13 UTC, Nordlöw wrote:
> Has anyone cooked up a generic D struct that groups together min
> and max values of a type and default-initializes them in the
> correct way?
>
> Something like
>
> struct Limits(T)
> {
> /* TODO: Fix purity of this by fixing Bytes.value() */
> auto init() @trusted /* pure */ nothrow { return
> tuple(T.max,
>
> T.min); }
> alias _minmax this;
> Tuple!(T,T) _minmax;
> }
> auto limits(T)() { return Limits!T(); }
> unittest {
> Limits!int x;
> dln(x);
> }
>
> I want min and max to default initialize to T.max, T.min so they
> are prepared for x = min/max(x, ...) arithmetic. But the code
> above doesn't work because the init() function isn't called and I
> don't know why. And I can't use default member initialization
> because I want `Limits` to work also with types such as `SysTime`
> when min and max are only know at run-time.
>
> I'm aware of `std.datetime.span` but it isn't generic.
>
> Ideas anyone?
import std.stdio;
import std.typecons;
struct Limits(T)
{
auto _minmax = tuple(T.min, T.max);
alias _minmax this;
}
void main()
{
auto a = tuple(int.min, int.max);
a[1] = 2;
writeln(a);
Limits!int x;
writeln(x._minmax);
writeln(x);
x[0] = 1;
writeln(x);
writeln("end");
}
I'm not sure what you want to do.
|
Copyright © 1999-2021 by the D Language Foundation