July 08, 2014 Re: Incomplete types question | ||||
---|---|---|---|---|
| ||||
Posted in reply to NoUseForAName | NoUseForAName:
> Thanks, that is what I was looking for.
Why do you need a public pointer type but private struct type?
Bye,
bearophile
|
July 08, 2014 Re: Incomplete types question | ||||
---|---|---|---|---|
| ||||
Posted in reply to NoUseForAName | On Tuesday, 8 July 2014 at 11:42:54 UTC, NoUseForAName wrote:
> On Tuesday, 8 July 2014 at 11:16:52 UTC, Marc Schütz wrote:
>> Your example above doesn't work, because it would be interpreted as a redefinition of the struct. Instead, you can use a public alias to a private type:
>>
>> // my_module.d:
>>
>> private struct MyStructImpl {
>> int x;
>> }
>>
>> public alias MyStructPtr = MyStructImpl*;
>>
>> void doSomething(MyStructPtr foo) {
>> ...
>> }
>>
>> // my_main_program.d:
>>
>> MyStructPtr bar; // OK
>> MyStructImpl foo; // Error: my_module.MyStructImpl is private
>
> Thanks, that is what I was looking for.
Addendum: You also need to protect the members of MyStructImpl, like so:
private struct MyStructImpl {
private: // or `package:`
int x;
}
Otherwise, they would still be accessible via dereferencing. (Don't worry, you _can_ access private members inside the module the struct is declared in, as access protection in D only applies across module boundaries.)
|
July 08, 2014 Re: Incomplete types question | ||||
---|---|---|---|---|
| ||||
Posted in reply to bearophile | On Tuesday, 8 July 2014 at 11:55:01 UTC, bearophile wrote: > NoUseForAName: > >> Thanks, that is what I was looking for. > > Why do you need a public pointer type but private struct type? As the OP wrote: > In C my favorite way of achieving encapsulation is to use incomplete types. (Also known as PIMPL.) In C, it's the only type-safe way to get encapsulation, AFAIK. In languages with access protection, it's probably not as useful, but I'm sure it has its applications... |
July 08, 2014 Re: Incomplete types question | ||||
---|---|---|---|---|
| ||||
Posted in reply to Marc Schütz | On Tuesday, 8 July 2014 at 12:04:40 UTC, Marc Schütz wrote:
> Addendum: You also need to protect the members of MyStructImpl, like so:
>
> private struct MyStructImpl {
> private: // or `package:`
> int x;
> }
>
> Otherwise, they would still be accessible via dereferencing.
Thanks again.
|
July 08, 2014 Re: Incomplete types question | ||||
---|---|---|---|---|
| ||||
Posted in reply to bearophile | On 07/08/2014 03:35 AM, bearophile wrote: > Ali Çehreli: > >> 1) Put the opaque type and its functions into a .di file: > > [...] > > It seems your answer has scared NoUseForAName off. Next times we need to > be more careful, and suggest a D-idiomatic solution instead. > > Bye, > bearophile I should have first asked what the need was. Ali |
Copyright © 1999-2021 by the D Language Foundation