Tuples, CTFE, and Sliding Template Arguments

Nickolay Bukreyev buknik95 at ya.ru
Sat Jan 13 02:13:20 UTC 2024


On Friday, 12 January 2024 at 23:04:58 UTC, Timon Gehr wrote:
> I.e., you can use `enum` in a function argument list and you 
> have to default-initialize them. This means that this parameter 
> always needs to have exactly that value.
>
> Then, the arguments matched to an `enum` parameter are 
> evaluated at compile time and matched against the initializer.

Looks promising, but I have a question. Will this work?

```d
void pluto(){ }

void pluto(string s, Args...)(enum string x = s, Args args){
     pragma(msg, s);
     pluto(args); // <-
}

pluto("abc", "def", "ghi"); // pluto!("abc", string, string)
```

I’m afraid it can’t. When we call `pluto(args)`, `args` are not 
compile-time-known anymore. How can you overcome this?

---

I still think that Walter’s idea of relaxing requirements on 
alias parameters is the simplest yet general enough and is not 
limited to interpolations.

```d
struct Interpolation {
     immutable(string)[ ] parts;
}

void fooImpl(Interpolation interp, Args...)(Args args) { ... }

template foo(Interpolation interp, args...) {
     alias foo = fooImpl!interp(args);
}

void main() {
     string name = "Steve";
     int fourty = 40;
     foo!(i"Hello, $name, I see you are $(fourty + 2) years old.");
     // Desugars to:
     foo!(Interpolation(["Hello, ", "name", ", I see you are ", 
"fourty + 2", " years old."]), name, fourty + 2);
     // `foo!(...)` expands to:
     fooImpl!(Interpolation(["Hello, ", "name", ", I see you are 
", "fourty + 2", " years old."]))(name, fourty + 2);
}
```

This almost works now, except 1) you cannot pass `fourty + 2` to 
a template parameter, 2) you cannot do `alias foo = 
fooImpl!interp(args)`.

To say it another way, it should be allowed to instantiate a 
template with something unmangleable, but in that case the 
template must not declare anything that requires mangling 
(functions, variables, structs, unions, classes; uncertain about 
enums).

This approach has an advantage over several other proposals: if 
something is being accessed at compile time, you must indicate it 
clearly by putting an exclamation mark at the call site.


More information about the Digitalmars-d mailing list