How to get number of parameters in lambda?

Andrey Zherikov andrey.zherikov at gmail.com
Tue Mar 9 14:22:44 UTC 2021


On Tuesday, 9 March 2021 at 03:08:14 UTC, Paul Backus wrote:
> 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);

Yes, I can do some magic with this.

>> 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.

In case of function template this is possible but the original 
question was about lambdas. There is no way that lambda can 
change number of parameters during instantiation, am I right?


More information about the Digitalmars-d-learn mailing list