On 17.04.2012 12:28, "Erèbe" wrote:
Hi,
I'm working on some metaprogramming code which implement a Factory and
generate an enum from a list of string.
So here my questions :
1) The documentation say mixin templates could take as
TemplateParameterList
a "TemplateParameter , TemplateParameterList" but all my tried to
instaciate this template failed lamentably.
mixin template Foo(T, R...)
{
anotherTemplate!(T);
Foo!(R);
}
mixin Foo!( string, string, string);
Is something wrong with variadic template and mixin, do i miss something ?
2) Below some code I writed and I wanted to know if you have some advice
to improve it (Right maner to do it, TypeChecking, Safety, ...) <-
variaidc arguments
The code is working is purpose is to create an enum of commands and to
create a factory which returns me the command associated to a string.
Thanks !
===========================Code============================================
import std.stdio;
import std.traits;
import std.conv;
//Use to create the enums of every commands
mixin template enumGenerator( T... )
{
template generate( T... )
{
enum string value = T[0] ~ ", " ~ generate!( T[2..$] ).value;
}
template generate() { enum string value = "UNKNOW"; }
//Here the creation of the enum
mixin("enum Command { " ~ generate!(T).value ~ "};");
}
//Generate a function which return a command in regard of a string
mixin template factoryGenerator( T... )
{
template generate( T... )
{
enum string value = "if( cmd == \"" ~ T[1] ~ "\")"
~ "return Command." ~ T[0] ~ ";"
~ "else "
~ generate!(T[2..$]).value;
Stick in the magic pragma(msg, value); in here you won't regret it ;)
}
Another important thing to note here is that you should really
reconsider using plain if/else if it's a production code not some toy to
learn meta programming.
At very least try to generate switch over strings but I don't think any
D compiler optimizes it. (but it should in future)
Real world options are binary search on string table or even better
built-in hash table.
--
Dmitry Olshansky