On Wednesday, 14 November 2018 at 18:05:55 UTC, Adam D. Ruppe wrote:
On Wednesday, 14 November 2018 at 16:28:19 UTC, Radu wrote:
Looks like that there is no easy way to extract a function parameters UDA list.

Indeed, the only way I can find is kinda crazy:

---
void foo(int f, @("test") string s) {}

void main() {
        static if(is(typeof(foo) Params == __parameters))
pragma(msg, __traits(getAttributes, Params[1..2])); // get the second param
}
---


So, the process is:

1) alias the params with the static if + is() statement (this is what std.traits.Parameters does internally)

2) slice the params! using params[0] will not work, but params[0 .. 1] will.

3) get the attributes using the language function

Has anybody come up with a better solution yet? And why does __traits(getAttributes, Parameters!foo[0]) not work in the first place?

I am asking because I ran into a problem which does not seem solvable to me using the above workaround:

I would like to iterate over all parameters of a function using static foreach and then process each parameter's UDAs. But by using static foreach on the parameter tuple, slicing it is not possible anymore, so the suggested workaround does not work in this case :(

The error does not appear if all parameters of the function are symbols (e.g. structs), but it still does not work as expected because the UDAs simply get dropped when iterating over the parameter tuple. Here is an example:

import std;

struct Test
{}

void foo(@(1) Test x)
{
}

void main()
{
    alias Params = Parameters!foo;
    pragma(msg, Params);
    static foreach(P; Params)
    {
        pragma(msg, P);
        static foreach(uda; __traits(getAttributes, P))
        {
            pragma(msg, uda);
        }
    }
}

This prints

(@(1) Test)
Test

but I would expect it to print something like

(@(1) Test)
@(1) Test
@(1)

Reply via email to