Proposal: Support for objects in switch statements

bauss jj_1337 at live.dk
Sun Nov 5 11:01:04 UTC 2017


On Wednesday, 1 November 2017 at 01:16:32 UTC, solidstate1991 
wrote:
> After I started to alter my graphics engine to use the multiple 
> kinds of bitmaps (now using multiple language features, like 
> templates and aliases) on one layer, I noticed that type 
> detection of bitmap objects would be easier and better 
> readable, if instead of:
>
> if(bitmapObject.classinfo == typeof(Bitmap4Bit)){
> ...
> }else if(bitmapObject.classinfo == typeof(Bitmap8Bit)){...
>
> I could easily use this:
>
> switch(bitmapObject.classinfo){
> case typeof(Bitmap4Bit):
> ...
> case typeof(Bitmap8Bit):
> }
>
> On the other hand I cannot really think other uses for such 
> language feature, maybe with structs.

While it's not entirely ideal something like this works.

```
template ClassName(T, string mod = __MODULE__)
{
	enum ClassName = mod ~ "." ~ T.stringof;
}

@property string className(T)(T o)
{
	return o.classinfo.toString();
}
```

Example:

```
final switch (bitmapObject.className)
{
	case ClassName!Bitmap4Bit: ... break;
		
	case ClassName!Bitmap8Bit: ... break;
}
```


More information about the Digitalmars-d mailing list