Is it possible to elegantly craft a class that can be used as shared and as normal?

Gary Willoughby dev at nomad.so
Mon Mar 3 08:42:09 PST 2014


On Monday, 3 March 2014 at 12:07:15 UTC, Tolga Cakiroglu wrote:
>> Have you got a small example?
>
> import std.stdio;
>
> class Test{
> 	private int number;
>
> 	public void setNumber( int newValue ) shared{ number = 
> newValue; }
>
> 	public int getNumber() shared{ return number; }
> }
>
> void main(){
> 	auto test = new Test();
>
> 	(cast(shared)test).setNumber( 5 );
>
> 	writeln("Value = ", (cast(shared)test).getNumber() );
> }
>
> But do not forget the fact that because of the object `test` is 
> not shared, therefore the attribute `number` is not shared. 
> Thus, this will not be working multi-threded.

I still don't understand this example. To be more clear lets take 
the following class:

class Test
{
	private int number;

	public void setNumber(int newValue)
	{
		number = newValue;
	}

	public int getNumber()
	{
		return number;
	}
}

I need to instantiate that class twice like this:

auto a = new Test();
auto b = new shared Test();

And be able to use the methods of 'a' and 'b' without an error. 
How can i do this without overloading the methods is the big 
question. Casting the object is not an option in my particular 
use case.


More information about the Digitalmars-d-learn mailing list