Overloading struct members (or cast?)
    Steven Schveighoffer via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Tue Nov 18 11:01:53 PST 2014
    
    
  
On 11/18/14 1:28 PM, Ali Çehreli wrote:
> On 11/18/2014 07:32 AM, Wsdes wrote:
>
>  >             Error: need 'this' for 'string' of type 'const(char*)'
>
> Reduced:
>
> struct S
> {
>      union Value
>      {
>          const char* myString;
>      }
> }
>
> void main()
> {
>      auto s = S();
>      auto mine = s.Value.myString;    // ERROR
> }
>
> You may be thinking that Value introduces a name scope so that you can
> reference its myString by Value.myString.
>
> You have two options:
>
>
> a) Remove Value so that it is an anonymous union. myString becomes a
> direct member of S:
>
> struct S
> {
>      union    // <-- Anonymous
>      {
>          const char* myString;
>      }
> }
>
> void main()
> {
>      auto s = S();
>      auto mine = s.myString;    // <-- No more Value
> }
>
>
> b) Make S have an actual member of type Value:
>
> struct S
> {
>      union Value
>      {
>          const char* myString;
>      }
>
>      Value value;    // <-- Added
> }
>
> void main()
> {
>      auto s = S();
>      auto mine = s.value.myString;    // <-- Note lower initial
> }
>
> Ali
>
This works in C++:
struct S
{
    union
    {
       const char *myString;
    } Value;
};
But the issue is that D does not require the semicolon at the end of the 
struct, so by the closing brace, it is done with the union.
the closest solution you can get is the last one you said.
I never even considered that you can't make an anonymous struct or union 
type and assign it to a member in D. Not sure if we really need to 
support it though.
-Steve
    
    
More information about the Digitalmars-d-learn
mailing list