On Fri, Jul 17, 2009 at 12:20 PM, Nick Sabalausky<[email protected]> wrote: > "dsimcha" <[email protected]> wrote in message > news:[email protected]... >>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. >> } > > I don't see a real legitimate point to this. If you need something from a > module not provided by a public interface (or protected sub-classing) than > that needs to be properly added to the module's interface. Otherwise you're > just asking for your code to be broken (in a way that may *or* may not be > fixable) the moment the module you're hacking into is updated. Why hack it, > when you could just make a proper added feature? Sure, there may be > source-not-available stuff, but if you need some extra feature from a > library that doesn't have source available, and the lib's developers aren't > receptive to your need, then you're just simply using the wrong library > anyway.
If you can get the offset of a private member you can always do some pointer arithmetic to get the offset to the member you want to change. cast(Thing)(cast(void*)(object) + offsetofPrivateMember); Or something like that which looks appropriately evil given that you're doing something you're not supposed to. I would much rather see variants of cast that guarantee they won't reinterpret. cast(int)IThoughItWasANumberButItsAnObject. Eek. --bb
