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

Paul Backus snarwin at gmail.com
Tue Aug 17 20:13:59 UTC 2021


On Tuesday, 17 August 2021 at 19:53:52 UTC, james.p.leblanc 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)) { ... }
>>
>>
>> T
>
> 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.
>
> Best Regards,
> James

FYI: in this particular case, you can use std.meta.staticIndexOf 
instead of writing the recursion out yourself:

     import std.meta: staticIndexOf;
     enum isAmong(T, S...) = staticIndexOf!(T, S) >= 0;

Docs: https://phobos.dpldocs.info/std.meta.staticIndexOf.html


More information about the Digitalmars-d-learn mailing list