Reducing variadic template combinatorics (C++ was onto something)

Steven Schveighoffer schveiguy at gmail.com
Tue Oct 14 16:35:51 UTC 2025


On Tuesday, 14 October 2025 at 15:35:48 UTC, Dennis wrote:
> On Tuesday, 14 October 2025 at 14:44:56 UTC, Steven 
> Schveighoffer wrote:
>> Right, if nothing else it is a "best practice" on how to avoid 
>> template bloat. But if there is a way we can convey to the 
>> compiler this pattern, it would be very nice!
>
> I don't see the difference between the two, isn't the following 
> both a "best practice" as well as conveying the pattern to the 
> compiler?
>
> ```D
> void f(T...)(T args) if (T.length > 1)
> {
>     foreach (arg; args)
>         f(arg);
> }
>
> void f(T)(T arg)
> {
>     // Implementation
> }
> ```

Like if there were some way for the function author to identify 
that the variadic args are going to be looped independently, the 
compiler can save the code generation per type.

I don't know, maybe it's not worth the effort.

The idea is to keep the normal parameter list style, but the 
compiler rewrites it to cacheable templates. Either by being 
clued in that the variadic list is going to be processed this 
way, or by detecting it itself.

For example, if it can tell that the loop body doesn't use 
anything except the element, then it could rewrite the function 
as a standalone template automatically. Sort of like a lambda can 
detect whether it can be a function or delegate based on whether 
it uses any data from the surrounding frame.

I just feel like when your function is just doing a foreach over 
the tuple, it's a waste for the function to even exist, since you 
created the tuple in the first place!

The whole impetus for this is someone in one of my projects wants 
to change a function from a typesafe variadic into a template 
variadic. I'm hesitant to bloat the code this way for the sake of 
a new feature.

I've written a lot of variadic functions where the code mostly 
just loops over the variadic and does the same thing to each 
parameter independently. The bloat is always annoying but it's 
the best user API available in D.

-Steve


More information about the Digitalmars-d mailing list