www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Doubt about alias this

reply d coder <dlang.coder gmail.com> writes:
Greetings

Kindly take a look at the code below. I am using alias this with a function
that returns by value. I believe in such cases the alias should not take
affect when an instance of foo is being used as an lvalue. As a result
elements of bar should not have been visible inside the constructor of foo.

Please comment. Is this a bug?

Regards
- Puneet

struct bar (bool B, N...) {
  int n = 0;
}

struct foo (N...) {
  bar!(true, N) _bar = void;

  bar!(true, N) getN() {
    return _bar;
  }

  alias getN this;

  public this(T) (T other)
    if (is(T unused : int)) {
    n = other;
  }
}


void main() {
  import std.stdio;
  foo!8 a = 42;
  writeln(a.n);
}
Dec 06 2012
parent "Phil Lavoie" <maidenphil hotmail.com> writes:
Hi,

I tested the code you provided and extended it a little and here 
is the result:

struct bar (bool B, N...) {
  int n = 0;
}

struct foo (N...) {
  bar!(true, N) _bar = void;

  bar!(true, N) getN() {
    return _bar;
  }

  alias getN this;

  public this(T) (T other)
    if (is(T unused : int)) {
    n = other;
  }
}

void aFunc( bar!( true, 8 ) zeBar ) {
   //Subtyping compiles.
}

bar!( true, 8 ) aSecondFunc() {
   return bar!( true, 8 )();
}

struct toto{
   size_t payload;
}

toto aThirdFunc() {
   return toto();
}

void main() {
  import std.stdio;
  foo!8 a = 42;
  writeln(a.n); //Prints 0, as it should.
  aFunc( a ); //The alias this correctly allows for subtyping, as 
advertised
  a.getN().n = 3; //Allowing for rvalue manipulation is indeed 
weird, but apparently in a coherent fashion, not just for the 
alias this case.
  writeln(a.n); //Still prints 0, as it should.
  aSecondFunc().n = 4;
  aThirdFunc().payload = 10; //Without alias this, without 
templates, juste plain rvalue. Another coherent example, yet 
questionably permitted.
}

Therefore, your question, I believe, is more related to rvalues 
directly rather than alias this, if I get your meaning right. The 
question is still very relevant and I was surprised to find out 
about the current behaviors of rvalues.
Dec 06 2012