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

Stanislav Blinov stanislav.blinov at gmail.com
Mon Mar 3 09:17:23 PST 2014


On Monday, 3 March 2014 at 16:42:10 UTC, Gary Willoughby wrote:

> 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.

You can't and you shouldn't be able to. Why are you so inclined 
on subverting the type system? If you're sharing an instance that 
doesn't support 'shared', then you're providing thread-safety 
mechanisms (i.e. synchronization) and cast away shared. If you're 
sharing an instance that does support 'shared', it should provide 
its own thread-safety mechanisms (that you shouldn't care about 
beyond documentation).

Note that even using plain operators on shared *scalars* is 
disallowed (though not yet implemented, 
https://d.puremagic.com/issues/show_bug.cgi?id=3672). Because 
implementation of those operators on shared variables is supposed 
to be different (i.e. atomicOp). The same goes for classes and 
structs too: 'void method()' and 'void method() shared' can't be 
expected to have the same implementation (and wouldn't).

Were it different, there would be no sense in explicit sharing.


More information about the Digitalmars-d-learn mailing list