How to pass alias as template parameter?

Paul Backus snarwin at gmail.com
Mon Aug 27 16:23:30 UTC 2018


On Monday, 27 August 2018 at 09:50:01 UTC, Andrey wrote:
> alias Pair(alias key, alias value) = AliasSeq!(key, value);
> alias Pairs = AliasSeq!(Pair!(Option.First, 
> handler!(Option.First)), Pair!(Option.Second, 
> handler!(Option.Second)), handler);

You can't nest AliasSeqs. If you examine Pairs with pragma(msg, 
...), you'll see that the inner AliasSeqs have been expanded, and 
their members inserted into the outer sequence. As a result, when 
you attempt to iterate over the pairs later, you're actually 
iterating over the individual Options and handlers, one at a time:

> 	        static foreach(pair; pairs)
> 	        {
> 	            case pair.key:
> 	                pair.value(args, i);
> 	                break;
> 	        }

Also, you can't use the dot operator to access parameters of a 
template like that.

>>onlineapp.d(52): Error: template instance `parseArgs!("-first", 
>>handler, "-second", handler, handler)` does not match template 
>>declaration parseArgs(alias sequence)(ushort index, string[] 
>>args)

Here again, your AliasSeq "Pairs" is being expanded into multiple 
template arguments, rather than being passed as a single one. If 
you want to pass an AliasSeq to a template, you have to use a 
variadic template.

Further reading:
https://dlang.org/spec/template.html#variadic-templates
https://dlang.org/articles/ctarguments.html


More information about the Digitalmars-d-learn mailing list