A pattern I'd like to see more of - Parsing template parameter tuples

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue May 22 11:08:13 UTC 2018


On Monday, May 21, 2018 14:07:45 Jacob Carlborg via Digitalmars-d wrote:
> On Monday, 21 May 2018 at 00:13:26 UTC, Ethan wrote:
> > Code for context:
> > https://github.com/GooberMan/binderoo/blob/master/binderoo_client/d/src/
> > binderoo/util/enumoptions.d
> >
> > Something struck me at DConf. I was watching the dxml talk and
> > hearing about all these things that weren't being implemented
> > for one reason or another. And I was thinking, "But what if I
> > want those things?" Being D, it'd be pretty easy to opt in to
> > them with template parameters and static if controlling what
> > code gets executed at runtime.
> >
> > But that brings up a bit of an annoying thing. Namely, the old
> > school way of doing such things:
> >
> > class SomeObject( bool option1, bool option2, Flags iHateBools
> > = Flags.Default, int
> > ohIDontWantThisToBeDefaultedButRefactoringSucks = -1 )
> > {
> > }
> >
> > Pretty obnoxious design pattern.
> >
> > But we're in D. We can do much better. It makes sense to do the
> > following:
> >
> > class SomeObject( LooseOptions... )
> > {
> > }
>
> Unless I'm missing something we can do a lot better in D :
>
> struct Options
> {
>      bool foo;
>      bool bar;
>      int a;
>      string b;
> }
>
> class SomeObject(Options options)
> {
>      static if (options.foo)
>      {
>      }
> }
>
> No magic templates or anything fancy.
>
> --

That's basically what dxml does except that it takes advantage of the fact
that each member is a different type (because each is a differnt instance of
std.typecons.Flag) so that it can have a variadic function which takes any
of the arguments in any order. e.g.

enum config = makeConfig(SkipComments.yes, SplitOnEmpty.yes);
auto range = parseXML!config(xml);

or

auto range = parseXML!(makeConfig(SkipComments.yes, SplitOnEmpty.yes))(xml);

http://jmdavisprog.com/docs/dxml/0.3.2/dxml_parser.html#.Config
http://jmdavisprog.com/docs/dxml/0.3.2/dxml_parser.html#.makeConfig
http://jmdavisprog.com/docs/dxml/0.3.2/dxml_parser.html#.parseXML

- Jonathan M Davis



More information about the Digitalmars-d mailing list