www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Generic Span/Limits/MinMax Type

reply =?UTF-8?B?Ik5vcmRsw7Z3Ig==?= <per.nordlow gmail.com> writes:
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?
Jan 20 2014
parent "sclytrack" <sclytrack fake.com> writes:
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.
Jan 20 2014