www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - alias this and initialisation

reply Danni Coy <danni.coy gmail.com> writes:
can anybody tell me why

struct S
{
    int x;
    alias x this;
}

void test()
{
    S s;
    s = 8; // this works
    S s = 8 // but this does not?
}
May 24 2020
next sibling parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 5/24/20 6:35 PM, Danni Coy wrote:> can anybody tell me why
 struct S
 {
      int x;
      alias x this;
 }

 void test()
 {
      S s;
      s = 8; // this works
      S s = 8 // but this does not?
 }
alias this is for implicit conversion, which requires an object to convert from. The second case above is about constructing an object. That's probably why it works that way. Ali
May 25 2020
prev sibling next sibling parent Adam D. Ruppe <destructionator gmail.com> writes:
On Monday, 25 May 2020 at 01:35:47 UTC, Danni Coy wrote:
     s = 8; // this works
     S s = 8 // but this does not?
 }
alias this only applies if you already have an object. Construction is too soon. You can add a constructor to make that work though.
May 25 2020
prev sibling parent lalit.singhh <lalit.singhh007 gmail.com> writes:
On Monday, 25 May 2020 at 01:35:47 UTC, Danni Coy wrote:
 can anybody tell me why

 struct S
 {
     int x;
     alias x this;
 }

 void test()
 {
     S s;
     s = 8; // this works
     S s = 8 // but this does not?
 }
May 25 2020