The design of the hooks in std.experimental.checkedint

Jacob Carlborg via Digitalmars-d digitalmars-d at puremagic.com
Sat Jun 3 08:59:30 PDT 2017


I've been looking a bit at the design of the hooks in 
std.experimental.checkedint. Due to all hooks being optional there's 
quite a few "static if" in the implementation of checkedint to check if 
a hook is implemented.

Wouldn't it be simpler if all hooks were required and a default 
implementation was provided instead? Currently the Abort hook is the 
default hook that defines a couple of hooks but not all of them. If a 
default hook is instead implements all hooks but is implemented as a 
template it can be mixed in into custom hooks that want to change the 
behavior. For example, I want a hook that only defines the default 
value. Today that would look like this:

struct DefaultValueHook
{
     static T defaultValue!(T)() { return 1; }
}

If all hooks were required to be implemented but a default 
implementations would be provided it would look like this instead:

mixin template DefaultHook()
{
     T defaultValue!(T)() { return T.init; }
     ... // the rest of the hooks
}

struct DefaultValueHook
{
static:

     mixin DefaultHook; // provides default implementation for all hooks

     T defaultValue!(T)() { return 1; } // "overrides" defaultValue 
defined in DefaultHook
}

One extra line of could is required, the mixin.

It should also be simpler if you want to customize an existing hook but 
just override one of the hooks. Example:

struct DefaultValueHook
{
     mixin Warn;

     Dst onBadCast(Dst, Src)(Src src) { assert(0); }
}

In the implementation of Checked it would know that a hook is always 
provided and quite a few of the existing "static if" could be removed.

Thoughts?

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list