www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Getting RefCounted to work with classes

reply "Bienlein" <jeti789 web.de> writes:
Hello,

the code below compiles and runs fine. However, when I change 
Payload from struct to class I get compiler errors:

Error	1	Error: template instance 
std.typecons.RefCounted!(Payload, 
cast(RefCountedAutoInitialize)1) does not match template 
declaration RefCounted(T, RefCountedAutoInitialize autoInit = 
RefCountedAutoInitialize.yes) if (!is(T == 
class))	C:\Users\Nutzer\Windows Ordner\Documents\Visual Studio 
2013\Projects\RefCountedScratch\RefCountedScratch\main.d	26	

I tried many things, but nothing did it. Any help appreciated :-).
Thanks, Bienlein


import std.stdio;
import std.typecons;

struct Payload
{
	private int num = 0;

	this(int i)
	{
		num = i;
		writefln("Payload's constructor called");
	}

	~this()
	{
		 writefln("Payload's destructor called");
	}
}



int main(string[] argv)
{
     alias RefCounted!(Payload, RefCountedAutoInitialize.yes) Data;

     int bar = 12;
     Data data = Data(bar);

     return 0;
}
Aug 25 2014
parent reply "uri" <email ether.com> writes:
On Monday, 25 August 2014 at 21:14:03 UTC, Bienlein wrote:
 Hello,

 the code below compiles and runs fine. However, when I change 
 Payload from struct to class I get compiler errors:

 Error	1	Error: template instance 
 std.typecons.RefCounted!(Payload, 
 cast(RefCountedAutoInitialize)1) does not match template 
 declaration RefCounted(T, RefCountedAutoInitialize autoInit = 
 RefCountedAutoInitialize.yes) if (!is(T == 
 class))	C:\Users\Nutzer\Windows Ordner\Documents\Visual Studio 
 2013\Projects\RefCountedScratch\RefCountedScratch\main.d	26	

 I tried many things, but nothing did it. Any help appreciated 
 :-).
 Thanks, Bienlein


 import std.stdio;
 import std.typecons;

 struct Payload
 {
 	private int num = 0;

 	this(int i)
 	{
 		num = i;
 		writefln("Payload's constructor called");
 	}

 	~this()
 	{
 		 writefln("Payload's destructor called");
 	}
 }



 int main(string[] argv)
 {
     alias RefCounted!(Payload, RefCountedAutoInitialize.yes) 
 Data;

     int bar = 12;
     Data data = Data(bar);

     return 0;
 }
RefCounted does not work with classes. Classes are reference types already. The key is in the error message ...if(!is(T == class))... restricts the template to non-class types only. cheers, uri
Aug 25 2014
parent "Bienlein" <jeti789 web.de> writes:
On Tuesday, 26 August 2014 at 06:01:25 UTC, uri wrote:

 RefCounted does not work with classes. Classes are reference 
 types already.
Yep, that's the problem. I also got some suspicion, then surfed the Internet and found the information about it. Thanks for explaining the error message to me. Now it even seems obvious to me what it wants to say ;-). But you can define a var inside a struct that holds a class and this way I got it working with my class as well thanks to generics in D. Woohoo!
Aug 25 2014