how to pass a variable name in the template in this case?

Andrej Mitrovic andrej.mitrovich at gmail.com
Thu Aug 2 16:47:14 PDT 2012


On 8/3/12, Zhenya <zheny at list.ru> wrote:
> Huh,thank you,I understood.I just thought that by default alias
> parameter is an identifier.I was surprised then I saw that
> possible to pass value of variable,which is'nt enum.Could you
> explain me why it is?

I think alias can be seen as "pass by name". The template gets access
to a symbol whatever that symbol is (a variable, a type..). Whether or
not you can instantiate the template depends on what you do inside the
template, for example the following is all legal because every symbol
has a .stringof property:

template Test(alias symbol)
{
    pragma(msg, symbol.stringof);
}

void main()
{
    alias Test!(1) x;

    enum int en = 1;
    alias Test!(en) y;

    int var;
    alias Test!(var) z;
}

But if you change the template so it tries to read what the value of
'symbol' stores you will get an error for the last instantiation:

template Test(alias symbol)
{
    pragma(msg, symbol);
}

void main()
{
    alias Test!(1) x;

    enum int en = 1;
    alias Test!(en) y;   // ok, can be read at compile time

    int var;
    // error: variable var cannot be read at compile time
    alias Test!(var) z;
}


More information about the Digitalmars-d-learn mailing list