Accessing mutable data that isn't

Jonathan M Davis jmdavisProg at gmx.com
Mon Nov 25 22:08:37 PST 2013


On Monday, November 25, 2013 18:34:30 Spott wrote:
> Why is rhs a purely runtime argument? I would think it would be
> known at compile time.

Function arguments are runtime entities, not compile-time entities and 
therefore cannot be used in places where a compile-time entity is required. 
e.g. this is illegal

auto foo(int i)(int j)
{
 return i * j;
}

auto bar(int k)
{
 return foo!k(5);
}

because k is not known at compile time. Yes, it's true that if a function is 
used during CTFE, then its function arguments would technically be known at 
compile time, as the compiler is in the middle of compiling your program, 
however, from the function's perspective, it's runtime. It just so happens 
that it's being run at compile time. e.g.

auto foo(int i)
{
 return i;
}

enum f = foo(5);

f must be known at compile time, so foo is called and run at compile time, but 
from foo's perspective, it's being run, not compiled. So, it can only do the 
things that it could do at runtime (plus whatever additional restrictions CTFE 
imposes - e.g. no I/O).

Template parameters are compile-time entities and thus must be known at 
compile time. However, aliases are a bit funny in that they alias the symbol 
rather than using its value, so apparently, under some set of circumstances, a 
template alias parameter can accept a runtime argument, because it's the 
symbol that gets used and not its value, meaning that its value is not 
calculated until runtime, so it works. But any normal template parameter's 
value must be known at compile time.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list