Template specialization ignores attributes (at least 'immutable')

Ali Çehreli acehreli at yahoo.com
Mon Feb 15 11:49:50 PST 2010


I've tried a function that reads an answer from the standard input:

T get_answer(T)(string question)
{
     dout.writef(question, ": ");

     T answer;
     din.readf(&answer);

     return answer;
}

That doesn't work for strings, as they are immutable and din.readf fails.

So I wrote a specialization for string, which uses the instantiation of 
the same template for char[] and adds an .idup at the end:

T get_answer(T : string)(string question)
{
     return get_answer!(char[])(question).idup;
}

That did not work, because even the get_answer!(char[]) call selects the 
string specialization.

Then I realized that a compile time 'if' works:

T get_answer(T : string)(string question)
     if (is (T == string))                 // <--- NECESSARY
{
     return get_answer!(char[])(question).idup;
}

That's cool but is a little silly, as it means "this is the 
specialization for string AND consider it only when T is a string."

Should attributes be considered for specializations as well?

Ali



More information about the Digitalmars-d mailing list