Thread overview | |||||
---|---|---|---|---|---|
|
November 10, 2015 When a variable is passed into a function, is its name kept somewhere for the function to acceess | ||||
---|---|---|---|---|
| ||||
Here is what I want to know: when a function is called, does this function can recovery the information about which variables pass their values into this function's arguments. I use the following example to show what I want to know. void main(){ int a = 1; writeln(fun(a.stringof, a)); } //to return "a is assigned to 1" string fun(string name, int x) return name~" is assigned to "~x; } For this example my question turns to become: can the name for fun be derived instead of passing to it? string fun(int x) //is there any way we can know that this value x is passed from the variable a in the main function? string name = the name of the variable which passes its value to x return name~" is assigned to "~x; } Please enlighten me if this can be done, thanks. |
November 10, 2015 Re: When a variable is passed into a function, is its name kept somewhere for the function to acceess | ||||
---|---|---|---|---|
| ||||
Posted in reply to DlangLearner | On Tuesday, 10 November 2015 at 14:14:33 UTC, DlangLearner wrote:
> Please enlighten me if this can be done, thanks.
If i understand you, you could use a templated function:
import std.stdio;
void foo(alias a)()
{
writefln("%s was passed in.", a.stringof);
}
void main(string[] args)
{
auto bar = "bar";
foo!(bar);
}
|
November 10, 2015 Re: When a variable is passed into a function, is its name kept somewhere for the function to acceess | ||||
---|---|---|---|---|
| ||||
Posted in reply to Gary Willoughby | On Tuesday, 10 November 2015 at 14:22:49 UTC, Gary Willoughby wrote:
> On Tuesday, 10 November 2015 at 14:14:33 UTC, DlangLearner wrote:
>> Please enlighten me if this can be done, thanks.
>
> If i understand you, you could use a templated function:
>
> import std.stdio;
>
> void foo(alias a)()
> {
> writefln("%s was passed in.", a.stringof);
> }
>
> void main(string[] args)
> {
> auto bar = "bar";
> foo!(bar);
> }
This is what I want. Thank you so much, this is a really elegant solution.
|
Copyright © 1999-2021 by the D Language Foundation