Compile Time versus Run Time
ag0aep6g via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jul 31 09:08:28 PDT 2017
On 07/31/2017 05:43 PM, Martin Tschierschke wrote:
> As a rookie in D programming I try to understand the power of templated
> functions with compile time parameters. With DMD 2.074 a compile time
> format
> (auto output = format!("Print this %s")(var);)
>
> was introduced, now we all know that very many of this format strings
> are immutable, so wouldn't it be cool to automatically detect this and
> use the compile time version?
>
> Without the need to think about it and to use an other syntax?
> Is this theoretically possible?
Kinda-sorta, but not really and you have to use the template syntax:
----
string format(alias fmt, A ...)(A args)
{
import std.format: sformat = format;
static if (__traits(compiles, { enum e = fmt; }))
return sformat!("(CT) " ~ fmt)(args);
else
return sformat("(RT) " ~ fmt, args);
}
void main()
{
import std.stdio: readln, writeln;
// CT
writeln(format!"Print this %s"(42));
// RT
auto fmt = readln();
writeln(format!fmt(42));
// Can't call it like this: format!(readln())(42);
// also still RT
auto fmt2 = "Print this %s";
writeln(format!fmt2(42));
// (somewhat surprisingly) CT
immutable fmt3 = "Print this %s";
writeln(format!fmt3(42));
}
----
More information about the Digitalmars-d-learn
mailing list