www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Private functions and allMembers

reply "Carl" <myemail mail.com> writes:
Here is some test code:

// --- start --- //
// main.d //
import std.stdio;
import extra;

void main()
{
	void function() func;

	foreach(mem; __traits(allMembers, __traits(parent, test)))
	{
		foreach(att; __traits(getAttributes, mixin(mem)))
		{
			if(att == "good") func = &mixin(mem);
		}
	}

	if(func) func();
	else writeln("func not assigned");
}

// extra.d //
import std.stdio;

 ("good")
public void test()
{
	writeln("test()");
}

 ("bad")
private void badtest()
{
}
// --- end --- //


main.d(13): Error: module main function extra.badtest is private
main.d(15): Error: module main function extra.badtest is private

I understand the need to prevent access to private members, but
how does one work around this?
Adding an if statment with __traits(compiles, mixin(mem)) still
gives errors. However, pragma(msg... shows it does return false
for the private function.
Jan 03 2014
parent "TheFlyingFiddle" <kurtyan student.chalmers.se> writes:
On Friday, 3 January 2014 at 18:30:56 UTC, Carl wrote:
 Here is some test code:

 // --- start --- //
 // main.d //
 import std.stdio;
 import extra;

 void main()
 {
 	void function() func;

 	foreach(mem; __traits(allMembers, __traits(parent, test)))
 	{
 		foreach(att; __traits(getAttributes, mixin(mem)))
 		{
 			if(att == "good") func = &mixin(mem);
 		}
 	}

 	if(func) func();
 	else writeln("func not assigned");
 }

 // extra.d //
 import std.stdio;

  ("good")
 public void test()
 {
 	writeln("test()");
 }

  ("bad")
 private void badtest()
 {
 }
 // --- end --- //


 main.d(13): Error: module main function extra.badtest is private
 main.d(15): Error: module main function extra.badtest is private

 I understand the need to prevent access to private members, but
 how does one work around this?
 Adding an if statment with __traits(compiles, mixin(mem)) still
 gives errors. However, pragma(msg... shows it does return false
 for the private function.
void main() { void function() func; foreach(mem; __traits(allMembers, extra)) { static if(__traits(compiles, mixin(mem))) foreach(att; __traits(getAttributes, mixin(mem))) { if(att == "good") func = &mixin(mem); } } if(func) func(); else writeln("func not assigned"); } This works for me. DMD 2.064.2
Jan 03 2014