A Perspective on D from game industry

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Wed Jun 18 09:11:26 PDT 2014


On Wed, Jun 18, 2014 at 07:58:56AM +0000, c0de517e via Digitalmars-d wrote:
> 
> >Actually I was talking about templates:
> >
> >	R find(R,T)(R range, T element)
> >		if (isInputRange!R && is(ElementType!R : T))
> >	{
> >		while (!range.empty)
> >		{
> >			if (range.front == element)
> >				break;
> >			range.popFront();
> >		}
> >		return range;
> >	}
> 
> http://en.wikipedia.org/wiki/Parametric_polymorphism
> 
> C++ Templates are more general than that, they do express this kind of
> polymorphism but that can be done without "full" metaprogramming
> (turing-complete ability of generating code at compile time).

You're talking about compile-time codegen? Like D's ctRegex perhaps?

	import std.regex;

	// Statically generates a regex engine that matches the given
	// expression.
	auto r = ctRegex!`(a+b(cd*)+)?z`;

I find this extremely awesome, actually. It's self-documenting (ctRegex
tells you it's a compile-time generated regex engine; the binary '!'
tells you it's a compile-time argument, the regex syntax is confined
inside the quoted ``-string, and doesn't spill out into language-level
operators, unlike C++'s Xpressive horror), and it's maximally efficient
because the matching engine optimization happens at compile-time,
whereas most regex libraries do the regex compilation at runtime.


[...]
> Also notice that really all this is expressible even in languages that
> have only dynamic polymorphism (subtyping) without performance
> penalties (YES REALLY).
> 
> People think that implementing interfaces is for some reason
> inherently slower than templates, the same they believe function
> pointers are slower than functors. It's FALSE. The ONLY reason why
> templates and functors can be faster is because they are always
> inline, the compiler knows exactly what to call without indirections.
> But that's only WORSE than the "indirect" alternatives, because
> interfaces and pointers afford you the option not to resolve
> everything statically, but if you want you can always inline
> everything (put the implementation in headers) and the compiler will
> perfectly know that it can directly call a given function without
> overhead...

This is a strawman argument. A template *can* be instantiated with base
class (or interface) arguments, and then you get *both* compile-time
*and* runtime polymorphism from the same template, i.e., the best of
both worlds.


T

-- 
Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald Knuth


More information about the Digitalmars-d mailing list