Fun determining the number of parameters using core reflect

Stefan Koch uplink.coder at googlemail.com
Sat Sep 11 10:15:56 UTC 2021


On Saturday, 11 September 2021 at 08:48:34 UTC, Stefan Koch wrote:
> Hi there,
>
> ```
> import core.reflect.reflect;
> @(core.reflect) uint nParameters(immutable string fName = 
> __FUNCTION__, immutable Scope _scope = currentScope())
> {
>     auto F = cast(const FunctionDeclaration)
>         nodeFromName(fName, ReflectFlags.NoParent | 
> ReflectFlags.NoFunctionbody, _scope);
>     uint params = cast(uint)F.type.parameterTypes.length;
>     return params;
> }
> ```

I can already hear you ask if that supports eponymous templates.
The answers is ... yes it does.

As of a few minutes ago :)

```
string nArgs(T...)(T args)
{
     static assert(nParameters == 4, "template has to be called 
with 4 arguments excat>
     return "reflection is cool";
}

pragma(msg, nArgs(1, 2, "trythis", 4.0));

// pragma(msg, nArgs(1, 2, "trythis", 4.0, 1)); // won't compile 
static assert fails
```

You can determine the type and names of the parameters passed in.
You can determine how they are used in the function body if there 
is a body.
I just realized a few minutes ago what interesting things allows 
you to do.




More information about the Digitalmars-d mailing list