How to get number of parameters in lambda?

Paul Backus snarwin at gmail.com
Tue Mar 9 03:08:14 UTC 2021


On Tuesday, 9 March 2021 at 02:24:07 UTC, Andrey Zherikov wrote:
> On Tuesday, 9 March 2021 at 01:38:52 UTC, Paul Backus wrote:
>> What's the larger problem you're trying to solve here?
>
> Just to make things simple: I have a 'caller' that calls some 
> function provided as an alias template argument and I want to 
> support different number of arguments (purpose is to provide 
> additional parameters if 'f' supports):
>
> void caller(alias f)()
> {
>     static if(/*one parameter*/)
>         f(1);
>     else static if(/*two parameters*/)
>         f(1, 2);
> }

If you know the arguments you want to call the function with, the 
easiest way to check if you can do it is with __traits(compiles):

static if (__traits(compiles, f(1)))
     f(1);
else static if (__traits(compiles, f(1, 2)))
     f(2);

> I understand that types are not available since they are 
> undefined until instantiation. But why can't I get argument 
> count? Is it possible that it can change during instantiation?

Yes, it's possible. For example:

template fun(T) {
     static if (is(T == int)) {
         void fun(T a, T b) {
             /* ... */
         }
     } else {
         void fun(T a) {
             /* ... */
         }
     }
}

Of course, code like this is rare in practice, but because it's 
technically possible, the compiler can't assume *anything* about 
a template function before it's been instantiated.


More information about the Digitalmars-d-learn mailing list