simple (I think) eponymous template question ... what is proper idimatic way ?

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Aug 17 20:59:58 UTC 2021


On Tue, Aug 17, 2021 at 07:53:52PM +0000, james.p.leblanc via Digitalmars-d-learn wrote:
> On Tuesday, 17 August 2021 at 19:44:29 UTC, H. S. Teoh wrote:
> > You could use a helper template and an AliasSeq for this:
> > 
> > 	template isAmong(T, S...) {
> > 		static if (S.length == 0)
> > 			enum isAmong = false;
> > 		else
> > 			enum isAmong = is(T == S) ||
> > 				isAmong(T, S[1..$]);
> > 	}
> > 
> > 	import std.meta : AliasSeq;
> > 	alias MyTypes = AliasSeq!(int, float, MySpecialStruct);
> > 
> > 	auto myFunc(T)(T a, T b) if (isAmong!(T, MyTypes)) { ... }
[...]
> Dear H.S. Teoh,
> 
> Wow!  That is absolutely beautiful ... I had never seen (or even
> imagined) a recursive template!  This expands my mind in a good
> way ... and is going into my toolbox immediately.
[...]

I didn't want to spoil your joy of discovery, but since others have
already done that -- beware of recursive templates, because if used too
often they can become a source of big slowdowns to your compilation
times (as well as the compiler consuming ridiculous amounts of memory).

Simple, linearly-recursive templates like this one are probably harmless
(unless you artificially generate pathologically-long lists of types).
But if the recursion gets too deep or grows superlinearly, you probably
want to consider alternative implementations instead. ;-)


--T


More information about the Digitalmars-d-learn mailing list