Aliasing current function template instance

Simen Kjærås simen.kjaras at gmail.com
Fri May 1 20:52:41 UTC 2020


On Friday, 1 May 2020 at 20:28:58 UTC, Jean-Louis Leroy wrote:
> Is it possible, inside a function template, to create an alias 
> to the instantiated function? IOW the equivalent of 
> __FUNCTION__, but yielding an alias?
>
> The closest I came is:
>
>   import std.string;
>   import std.traits;
>
>   void foo(T)(lazy T)
>   {
>     mixin(
>       "alias thisFunction = ",
>       __FUNCTION__[0..__FUNCTION__.lastIndexOf('.')],
>       ";");
>     pragma(msg, Parameters!thisFunction);
>   }
>
>   void main()
>   {
>     foo(0);
>     foo("");
>   }
>
>   dmd -c aliasthisfunction.d
>   (lazy int)
>   (lazy string)
>
> ...but (unsurprisingly) this fails in presence of overloads. 
> I.e. if I throw in:
>
>   void foo(T)(int, T);
>
> ...then I get:
>
>   aliasthisfunction.d(6): Error: template 
> `aliasthisfunction.foo` matches more than one template 
> declaration:
>   aliasthisfunction.d(4):     `foo(T)(lazy T)`
>   and
>   aliasthisfunction.d(20):     `foo(T)(int, T)`
>   ...
>
> Something I have overlooked? Any ideas?

This should work:

alias context(alias a) = __traits(parent, a);

void fun() {
     alias ctx = context!({})();
}

{} becomes a lambda inside fun(), so it's parent is fun(). The 
same could be done by introducing a symbol explicitly, but that 
pollutes the namespace. This template works inside functions, 
methods, lambdas, modules, structs, classes and interfaces.

--
   Simen


More information about the Digitalmars-d-learn mailing list