Templates with scope

bauss jj_1337 at live.dk
Wed Jul 21 10:45:31 UTC 2021


On Wednesday, 21 July 2021 at 10:08:10 UTC, bauss wrote:
> On Wednesday, 21 July 2021 at 09:06:52 UTC, Sönke Ludwig wrote:
>> Am 21.07.2021 um 09:16 schrieb bauss:
>>> Is there a way to make this logic work without using a mixin 
>>> template.
>>> 
>>> I'd prefer if using a plain template was possible, rather 
>>> than using a mixin template, because it introduces some extra 
>>> boilerplate.
>>
>> The symbol name is not available in the scope of the template, 
>> so that the `mixin(symbol.stringof)` doesn't work, but you can 
>> simply use the alias directly:
>>
>>     template CanCompile(alias symbol)
>>     {
>>         enum CanCompile = __traits(compiles, { symbol = 10; });
>>     }
>
> The problem is that I just saw I didn't describe my problem 
> very well, as I don't actually have the symbol at the given 
> time.
>
> I only had the symbol name and I use it to test if the symbol 
> is available because it comes from a __traits(allMembers) which 
> includes some symbols that makes it fail to compile if I try to 
> use the symbol directly without checking whether it compiles or 
> not.
>
> And this was the exact template I was trying to use:
>
> ```d
> template CanUseSymbol(string symbolName, string symbolAlias = 
> "symbol", string moduleAlias = "moduleImport")
> {
>   enum CanUseSymbol = __traits(compiles, { mixin("alias " ~ 
> symbolAlias ~ " = " ~ moduleAlias ~ "." ~ symbolName ~ ";"); });
> }
> ```
>
> For obvious reasons it doesn't work as you also mentioned, the 
> scope simply isn't available.
>
> But I can't use alias unfortunately in this case.
>
> I wish there was a way to return the symbols from allMembers, 
> instead of just the name of the symbols, that would solve this 
> problem.

I found a somewhat solution to it all by creating a template that 
used __traits(allMembers) and in the same scope tested the 
members and built a new list of members that were available and 
then simply used the generated list to loop through, so I didn't 
have to test the symbols outside of the template's scope.


More information about the Digitalmars-d mailing list