Simplify some C-style code

monkyyy crazymonkyyy at gmail.com
Wed Dec 25 17:40:12 UTC 2024


On Wednesday, 25 December 2024 at 16:41:05 UTC, sfp wrote:
> On Wednesday, 25 December 2024 at 07:57:04 UTC, monkyyy wrote:
>> static foreach, traits and mixin
>
> I was looking into this but I think I need some help getting 
> off the ground...
>
> This doesn't compile:
> ```
> enum Test { mixin("A, B, C") }
> ```

```

import std;
enum string[] domains=["Ball","Box","CsgDiff"];//could be from 
traits but I think traits when strings will do is bad
enum string[] lowerdomains=["ball","box","csgDiff"];//could be 
ctfe but... eh

mixin("enum DomainType{"~domains.joiner(",").array~"}");//array 
makes allot of range code simpler to work with, at costs of speed
string makeunion(){
	string o;
	o~="union{";
	foreach(i;0..domains.length){
	 o~=domains[i]~"!Dim ";
		o~=lowerdomains[i]~";";
	}
	o~="}";
	return o;
}
string makeconstructor(int i){
	string o;
	o~="this("~domains[i]~"!Dim "~lowerdomains[i]~"){\n";
	o~="this.type=DomainType."~domains[i]~";\n";
	o~="this."~lowerdomains[i]~"="~lowerdomains[i]~";}";
	return o;
}
unittest{
	//makeconstructor(1).writeln;
}
struct Ball(int i){}
struct Box(int i){}
struct CsgDiff(int i){}
struct Domain(int Dim){
	DomainType type;
	mixin(makeunion);
	static foreach(i;0..domains.length){
		mixin(makeconstructor(i));
	}
	void doSomething(){
		lable:switch(type){
			static foreach(E;DomainType.min..DomainType.max){
				case E: E.stringof.writeln; break lable;
			}
		default:
	}}
}
unittest{
	auto foo=Domain!1(Ball!1());
	foo.doSomething;
}
```


More information about the Digitalmars-d-learn mailing list