Just another example of missing string interpolation

Steven Schveighoffer schveiguy at gmail.com
Fri Oct 20 16:19:44 UTC 2023


On Friday, 20 October 2023 at 13:45:40 UTC, Steven Schveighoffer 
wrote:
> All the proposed solutions, including 1027, can be worked with 
> for most cases. It's just that the code to adapt 1027 to calls 
> except for printf and writef is awful. It doesn't handle other 
> situations at all.

I misspoke, 1027 doesn't actually handle `printf` very well, you 
still have to include the format specifiers for anything other 
than a `char *`. Only `writef` makes sense.

Whereas, with DIP1036, I [already 
wrote](https://forum.dlang.org/post/rv6f0l$ke7$1@digitalmars.com) 
an overload that works with `printf` without needing any 
specifiers, and is betterC compatible, it should lower to one 
call to `core.stdc.stdio.printf`.

```d
import core.stdc.stdio;
import std.traits;

struct interp(string s)
{
     static string toString() { return s; }
}

alias printf = core.stdc.stdio.printf;

auto printf(Args...)(Args args) if (isInstanceOf!(interp, 
Args[0]))
{
     static immutable formatStr = () {
         string result;
         foreach(T; Args)
             static if(isInstanceOf!(interp, T))
                 result ~= T.toString();
             else static if(is(T == int))
                 result ~= "%d";
             else static if(is(T : const(char)[]))
                 result ~= "%.*s";
             else static if(is(T == float) || is(T == double))
                 result ~= "%f";
             // .. and so on
         return result ~ "\0";
     }();

     mixin(() {
         string result = "return 
core.stdc.stdio.printf(formatStr.ptr";
         foreach(i, T; Args)
             static if(!isInstanceOf!(interp, T)){
                 static if(is(T : const(char)[]))
                     result ~= ", cast(int)args[" ~ i.stringof ~ 
"].length, args[" ~ i.stringof ~ "].ptr";
                 else
                     result ~= ", args[" ~ i.stringof ~ "]";
             }
         return result ~ ");";
     }());
}

extern(C) void main()
{
     string name = "Walter";
     int age = 42;
     // equivalent of printf(i"Hello, ${name}, you are ${age} 
years old.\n");
     printf(interp!"Hello, "(), name, interp!", you are "(), age, 
interp!" years old.\n"());
     printf("And normal printf works too, %s\n", name.ptr);
}
```

-Steve


More information about the Digitalmars-d mailing list