Idea: Context sensitive attribute functions.

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Jun 19 21:38:14 UTC 2018


On Tuesday, June 19, 2018 21:11:10 Dennis via Digitalmars-d wrote:
> On Tuesday, 19 June 2018 at 21:06:16 UTC, Dennis wrote:
> > On Tuesday, 19 June 2018 at 19:03:44 UTC, 12345swordy wrote:
> >> Why not use them if given the opportunity based on its context?
> >
> > You can do that if you want
>
> Although it doesn't seem to work in attribute interference of
> templates.
>
> ```
> void main() @nogc {
>      example();
> }
>
> void example()() {
>      int a = 8;
>      static if (__traits(compiles, new int(0))) {
>          writefln("writeln %d", a);
>      } else {
>          printf("printf %d", a);
>      }
> }
> ```
>
> onlineapp.d(5): Error: @nogc function D main cannot call
> non- at nogc function onlineapp.example!().example
>
> Maybe there's some workaround?

Whether a function is @nogc has nothing to do with where it's called from.
It has to do with what it calls. As such, new int(0) compiles just fine
inside of your example function, and that branch is compiled in, making it
so that the function is not @nogc. I am not aware of any way to make a
function's attributes depend on what calls it. The closest would be if you
changed what it did based on its template arguments - which would mean doing
something like passing a bool or flag indicating whether the function should
be compiled as @nogc or not. I don't think that it's possible to have a
function be compiled differently based on where it's called from. Attribute
inference is all about inferring the attributes of the templated function
based on its implementation, not adjusting its implementation based on where
it's used.

- Jonathan M Davis



More information about the Digitalmars-d mailing list