On 03/27/2013 12:22 AM, John Colvin wrote:
On Tuesday, 26 March 2013 at 23:00:40 UTC, Timon Gehr wrote:
...
Bad code. Use enum for compile-time constants.
This will work:
struct A{
void b(){
size_t y;
mixin(c!("y"));
}
template c(string x){
enum c = "while(" ~ x ~ " < 100){" ~ x ~ "++;}";
}
}
Perhaps you can enlighten me:
why does "const c" work if the template is outside the struct, but not
if it's inside?
const c has memory allocated at run time, it would need to be a field of
A. Because the number of template instantiations is not bounded a
priori, templates cannot be used to add fields to aggregates:
struct S{
template T(int x){
const s = x; // would need one field per instantiation
}
}
void main(){
S s;
auto a = S.T!0.s;
}
struct S{
template T(int x){
static const s = x; // static variables work
}
}
...
Because of a questionable patch (written by Kenji Hara, I think) some
time ago, the following works:
struct S{
template T(int x){
auto s = x; // implicitly static
}
}
...
I consider this bad language design.
Also, why doesn't "string c" work even outside of the struct, seeing as
it's value is completely defined at compile-time?
It is a design decision. Only variables initialized at compile time that
may not be mutated at run time can be read at compile time.
string c = "123";
immutable d = "1234";
void main(){
c = "456"; // may change, cannot be read at compile time
enum x = d; // may not change, can be read at compile time
}