www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Question about typeof(*this)

reply choi heejo <azurenote.enseed gmail.com> writes:
--0015175114a228ed2b0492c93929
Content-Type: text/plain; charset=UTF-8

hi there, please read this code:

import std.stdio;

struct test(T)
{
alias typeof(*this) type;
T a;
}


void main()
{
test!(int).type t;
 t.a = 123;
 writeln(t.a);
}

I guessed it would work. but the compiler said:

main.d(7): Error: can only * a pointer, not a 'test!(int)'
main.d(14): Error: template instance main.test!(int) error instantiating

what is the problem?

--0015175114a228ed2b0492c93929
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

<div>hi there, please read this code:</div><div><br></div><div>import std.s=
tdio;</div><div><br></div><div>struct test(T)</div><div>{</div><div><span c=
lass=3D"Apple-tab-span" style=3D"white-space:pre">	</span>alias typeof(*thi=
s) type;</div>
<div><span class=3D"Apple-tab-span" style=3D"white-space:pre">	</span>T a;<=
/div><div>}</div><div><br></div><div><br></div><div>void main()</div><div>{=
</div><div><span class=3D"Apple-tab-span" style=3D"white-space:pre">	</span=
test!(int).type t;</div>

<div><span class=3D"Apple-tab-span" style=3D"white-space:pre">	</span>t.a =

	</span></div>

ln(t.a);</div><div>}</div><div><br></div><div>I guessed it would work. but = the compiler said:</div><div><br></div><div><div>main.d(7): Error: can only= * a pointer, not a &#39;test!(int)&#39;</div> <div>main.d(14): Error: template instance main.test!(int) error instantiati= ng</div></div><div><br></div><div>what is the problem?</div><br> --0015175114a228ed2b0492c93929--
Oct 16 2010
parent Ivo Kasiuk <i.kasiuk gmx.de> writes:
choi heejo wrote:
 hi there, please read this code:
=20
=20
 import std.stdio;
=20
=20
 struct test(T)
 {
 alias typeof(*this) type;
 T a;
 }
=20
=20
=20
=20
 void main()
 {
 test!(int).type t;
=20
 t.a =3D 123;
=20
 writeln(t.a);
 }
=20
=20
 I guessed it would work. but the compiler said:
=20
=20
 main.d(7): Error: can only * a pointer, not a 'test!(int)'
 main.d(14): Error: template instance main.test!(int) error
 instantiating
=20
=20
 what is the problem?
=20

In D2, "this" in a struct is a reference type, not a pointer type. So just replace "typeof(*this)" by "typeof(this)" and then it should work. Ivo
Oct 17 2010