cast(public)

Robert Clipsham robert at octarineparrot.com
Sat Jul 18 03:25:04 PDT 2009


dsimcha wrote:
> I know I've probably mentioned this one here before, but it was buried in long
> threads.
> 
> Could we put a feature in the language that allows private member variables to
> be cast to public?  The idea is that, if a class/struct designer makes
> something private, they're saying it's a bad idea to mess with it, and that
> you do so at your own risk.  However, I think there needs to be a back door to
> cowboy this one, because otherwise private/protected is just too restrictive
> for a language like D.  It would work something like this:
> 
> struct Foo {
>     private uint bar;
> }
> 
> void main() {
>     Foo foo;
>     foo.bar++;  // error
>     (cast(public) foo.bar)++;  // Works.
> }

----
// There's a phobos function for this somewhere too,
// I couldn't be bothered looking for it though
import tango.core.Array : rfind;

T* get(T, char[] member, S)( ref S s )
{
   foreach( k, v; s.tupleof )
   {
      auto rdot = rfind( s.tupleof[k].stringof, "." ) + 1;
      if( s.tupleof[k].stringof[rdot .. $] == member )
      {
           static if( is( S == struct ) )
              return cast(T*)(cast(void*)&s + s.tupleof[k].offsetof);
           else
              return cast(T*)(cast(void*)s + s.tupleof[k].offsetof);
      }
   }
   return null;
}

void main()
{
   Foo foo;
   uint* bar = get!(uint, "bar")(foo);
   (*bar)++;
}
----

Who needs cast(public) anyways? :P



More information about the Digitalmars-d mailing list