www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - When a variable is passed into a function, is its name kept somewhere

reply DlangLearner <Bystander gmail.com> writes:
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.
Nov 10 2015
parent reply Gary Willoughby <dev nomad.so> writes:
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); }
Nov 10 2015
parent DLangLearner <DeepBlueParticle gmail.com> writes:
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.
Nov 10 2015