Retrieve the return type of the current function

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue May 5 17:40:51 UTC 2020


On Tuesday, May 5, 2020 11:11:53 AM MDT learner via Digitalmars-d-learn 
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?

A function is compiled completely independently of where it's used, and it's
the same regardless of where it's used. So, it won't ever have access to any
information about where it's called unless it's explicitly given that
information.

A function template will be compiled differently depending on its template
arguments, but that still doesn't depend on the caller at all beyond what it
explicitly passes to the function, and if the same instantiation is used in
multiple places, then that caller will use exactly the same function
regardless of whether the callers are doing anything even vaguely similar
with it.

So, if you want a function to have any kind of information about its caller,
then you're going to have to either explicitly give it that information via
a template argument or outright generate a different function with a string
mixin every time you use it. So, you could do something like

auto foo(T)(int i)
{
    ...
}

string bar(string s, int i)
{
    return!string(i);
}

or

string bar(string s, int i)
{
    return!(typeof(return))(i);
}

but you're not going to be have foo figure out anything about its caller on
its own.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list