Template alias parameter: error: need 'this' for ...

user1234 user1234 at 12.de
Fri Feb 24 14:22:17 UTC 2023


On Friday, 24 February 2023 at 12:00:41 UTC, Elfstone wrote:
> Seems like the same bug is still there after ten years.
>
>```d
> 	struct Bar
> 	{
> 		@("hello") int t;
> 	}
>
> 	static bool hasAttribute(alias F, T)()
> 	{
> 		bool result = false;
> 		foreach (a; __traits(getAttributes, F))
> 		{
> 			static if (is(typeof(a) : T))
> 			{
> 				result = true; // couldn't simply return true, 'cause the 
> compiler complains about "unreachable code".
> 			}
> 		}
> 		return result;
> 	}
>
> 	void main()
> 	{
> 		import std.stdio;
>
> 		writeln(hasAttribute!(Bar.t, string));
> 	}
>```

you can break using `goto`, restore `static` everywhere, and 
using local introspection determine whether the result exists.

```d
struct Bar
{
	@("hello") int t;
}

static bool hasAttribute(alias F, T)()
{
	static foreach (a; __traits(getAttributes, F))
	{
		static if (is(typeof(a) : T))
		{
			enum result = true;
			goto L0;
		}
	}
	L0:
	static if (is(typeof(result)))
		return result;
	else
		return false;
}

void main()
{
	import std.stdio;

	writeln(hasAttribute!(Bar.t, string));
}
```


More information about the Digitalmars-d-learn mailing list