Idioms for the D programming language

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Feb 12 00:26:09 UTC 2021


On Thu, Feb 11, 2021 at 12:12:36PM -0800, Walter Bright via Digitalmars-d-announce wrote:
[...]
> https://p0nce.github.io/d-idioms/

Not bad, but it seems to be missing some of the newer idioms.
Like the templated static this trick for transparently encoding
compile-time information at runtime.  For example:

	import std.regex;
	void main(string[] args) {
		foreach (arg; args) {
			if (arg.match(Re!`some.*regex(pattern)+`)) {
				... // do something
			}
		}
	}

	template Re(string reStr) {
		Regex!char re;
		static struct Impl {
			static this() {
				re = regex(reStr);
			}
		}
		string Re() { return re; }
	}

The Re template captures the regex string at compile-time and injects it
into Impl's static this(), which compiles the regex at program startup
at runtime, then the eponymous function Re() simply returns the
precompiled value.

The result:
- Regexes are automatically picked up at compile-time;
- But expensive compile-time generation of the regex (which consumes
  lots of compiler memory and slows down compilation) is skipped;
- Compilation of the regex happens only once upon program startup and
  cached, and thereafter is a simple global variable lookup.
- Multiple occurrences of the Re template with the same regex is
  automatically merged (because it's the same instantiation of the
  template).

D features used:
- compile-time string parameters
- static this()
- eponymous templates
- reuse of template instantiations that have the same arguments


[...]
> https://www.reddit.com/r/programming/comments/lhssjp/idioms_for_the_d_programming_language/

There doesn't appear to be any discussion happening here.


T

-- 
If it breaks, you get to keep both pieces. -- Software disclaimer notice


More information about the Digitalmars-d-announce mailing list