Best way to explicitly control the attributes of a template function

tsbockman via Digitalmars-d digitalmars-d at puremagic.com
Sat Apr 2 10:45:53 PDT 2016


Jack Stouffer and I have been working on a pull request for 
Phobos to enable runtime dispatch for field and property access:
     https://github.com/D-Programming-Language/phobos/pull/4070
(It's useful when directly porting code from dynamic languages 
like Python.)

Working with fields in this fashion is pretty easy, but I've hit 
a snag for property methods: if even one of the available 
property methods is impure, unsafe, etc., then the dispatch 
function must also be impure/unsafe/whatever.

In order for the dispatch function to be usable in 
pure/@safe/etc. code, it needs to filter out those property 
methods which are not. This is simple enough - except that 
*which* attributes are required cannot be inferred from the 
context; it must be explicitly specified by the user of the 
dispatch template - somehow...

A naive way to do it would be this:

     template example(string attrs = "pure @safe nothrow @nogc")
     {
         mixin("void example() " ~ attrs ~ " { /* do something */ 
}");
     }

Which could then be used like this:

     example!"pure @safe @SomeUDA"();

That's pretty ugly though, since it requires that all template 
functions with explicit attribute control be implemented as 
string mixins.

Is there a better way to do this? If not, I think consideration 
should be given (long-term) to adding an "attribute set" 
construct as a new type of template parameter.


More information about the Digitalmars-d mailing list