Retrieve the return type of the current function

Meta jared771 at gmail.com
Tue May 5 18:19:00 UTC 2020


On Tuesday, 5 May 2020 at 17:11:53 UTC, learner wrote:
> On Tuesday, 5 May 2020 at 16:41:06 UTC, Adam D. Ruppe wrote:
>
>> typeof(return)
>
> Thank you, that was indeed easy!
>
> Is it possible to retrieve also the caller return type? 
> Something like:
>
> ```
> int foo() {
>     return magic();
> }
>
> auto magic(maybesomedefaulttemplateargs = ??)() {
>     alias R = __traits(???); // --> int!
> }
> ```
>
> Mixin templates maybe?

You *can* use mixin templates to access the caller's scope, which 
means typeof(return) will refer to the caller's return type, 
instead of the callee's. However, there's no way to both mixin 
and call the mixin template in a single line, so it's not DRY:

int foo()
{
     mixin magic;
     return magic();
}

mixin template magic()
{
     alias CallerRet = typeof(return);
     CallerRet magic()
     {
         return CallerRet.init;
     }
}

void main()
{
     foo();
}

Maybe somebody else knows a way to get around having to first 
mixin magic.


More information about the Digitalmars-d-learn mailing list