Factory using an alias template parameter to set a member of the new tool ?

angel via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Feb 9 07:00:21 PST 2017


On Thursday, 9 February 2017 at 14:39:41 UTC, angel wrote:
> On Thursday, 9 February 2017 at 13:30:07 UTC, jkpl wrote:
>> I'm looking for a better way to do this, if possible:
>>
>> ```
>> class Tool
>> {
>>     string name;
>> }
>>
>> T namedTool(alias Variable, T)()
>> {
>>     T result = new T;
>>     result.name = Variable.stringof;
>>     return result;
>> }
>>
>> void main()
>> {
>>     Tool grep;
>>     grep = namedTool!(grep,Tool);
>>     assert(grep.name == "grep");
>> }
>> ```
>>
>> Ideally this would work like this:
>>
>> ```
>> Tool grep = namedTool!Tool;
>> assert(grep.name == "grep");
>> ```
>>
>> Possible ?
>
> Sorry, but this does not make much sense to me ...
> You expect "namedTool!Tool" to know that the name of the Tool 
> must be set to "grep".
> The expression evaluation proceeds from right to left, so at 
> the time of analyzing "namedTool!Tool", the compiler knows 
> nothing about "grep".
> On the other hand, if you supplied the "grep" variable, the 
> compiler could infer its type, like this:
> ```
> ...
> auto namedTool(alias Variable)()
> {
>     alias T = typeof(Variable);
>     T result = new T;
>     result.name = Variable.stringof;
>     return result;
> }
>
> void main()
> {
>     Tool grep;
>     grep = namedTool!(grep);
>     assert(grep.name == "grep");
> }
> ```

Or actually, maybe this will suite your case better:
```
template namedTool(T, alias Variable)
{
     enum namedTool = T.stringof ~ " " ~ Variable ~ " = new " ~ 
T.stringof ~ ";" ~
                      Variable ~ ".name = \"" ~ Variable ~ "\";";
}

void main()
{
     mixin(namedTool!(Tool, "grep"));
     assert(grep.name == "grep");
}
```


More information about the Digitalmars-d-learn mailing list