January 03, 2014 Private functions and allMembers | ||||
---|---|---|---|---|
| ||||
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. |
January 03, 2014 Re: Private functions and allMembers | ||||
---|---|---|---|---|
| ||||
Posted in reply to Carl | 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
|
Copyright © 1999-2021 by the D Language Foundation