[Issue 22091] Unexpected behaviour with variadic template param followed by default parameter

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Jun 29 09:33:59 UTC 2021


https://issues.dlang.org/show_bug.cgi?id=22091

Max Samukha <maxsamukha at gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |maxsamukha at gmail.com

--- Comment #1 from Max Samukha <maxsamukha at gmail.com> ---
(In reply to Sharon Hadas from comment #0)
> When using a variadic template parameter in a function, it is possible to
> define another parameter afterwards. This behaves in the expected way in
> most cases, however when the parameter is a default parameter, it is
> impossible to pass anything into it, since the variadic parameter seems to
> be greedy and always takes in whatever is passed to it.
> 
> Here's an example that shows this behaviour:
> 
> import std;
> void variadic(Args...)(Args args) {
>     writefln("variadic - Args len is %s", args.length);
>     variadic2(args, 5);
> }
> void variadic2(Args...)(Args args, int anotherArg = 4) {
>     writefln("variadic2 - Args len is %s, args is %s, anotherArg is %s",
> args.length, args, anotherArg);
> }
> void main()
> {
>     variadic();
> }
> 
> This example prints (seems to be consistent across compilers and operating
> systems):
> 
> variadic - Args len is 0
> variadic2 - Args len is 1, args is 5, anotherArg is 4
> 
> This is counterintuitive behaviour. I think the correct behaviour in this
> case would be for it to not compile.

FWIW, you can use explicit instantiation to work around this particular case:

import std;
void variadic(Args...)(Args args) {
    writefln("variadic - Args len is %s", args.length);
    variadic2!Args(args, 5);
}
void variadic2(Args...)(Args args, int anotherArg = 4) {
    writefln("variadic2 - Args len is %s, anotherArg is %s", args.length, args,
anotherArg);
}
void main()
{
    variadic();
}

variadic - Args len is 0
variadic2 - Args len is 0, anotherArg is 5

--


More information about the Digitalmars-d-bugs mailing list