A code example that shows why I don't like warnings

FeepingCreature feepingcreature at gmail.com
Fri Oct 18 16:43:54 UTC 2019


On Friday, 18 October 2019 at 16:38:38 UTC, Adam D. Ruppe wrote:
> Consider this code:
>
> -----
>
> string defaultFormat(alias method)() {
>         static foreach(attr; __traits(getAttributes, method))
>                 static if(is(typeof(attr) == string))
>                         return attr;
>         return "default";
> }
>
> void test() {}
> @("test") void test2() {}
>
> pragma(msg, defaultFormat!test);
> pragma(msg, defaultFormat!test2);
>
> void main() {}
>
> -----
>
>
> If you compile that with warnings enabled, you will get
>
> Warning: statement is not reachable

Behold, the shitty workaround:

string defaultFormat(alias method)() {
         alias attributes = __traits(getAttributes, method);
         static if (attributes.length == 0)
             	return "default";
         else static foreach(i, attr; attributes)
                 static if(is(typeof(attr) == string))
                         return attr;
            		else static if (i == __traits(getAttributes, 
method).length - 1)
             		return "default";
}

This does **not** spark joy. But it works.


More information about the Digitalmars-d mailing list