D's enums, std.conv.to, and IFTI rock my socks

Added: Jun 10, 2011

Note the bolded line:


		enum Color {
			red, blue, green
		}

		class Cgi {
			T request(T = string)(string name, T defaultValue = T.init) {
				try
					return to!T(get[name]);
				catch( ... )
					return defaultValue;
			}
		}

		auto c = cgi.request("color", Color.red);
	

Then, go to yoursite?color=whatever. It just works - to!enum(string) automatically works for the enum values, and it throws if it isn't there. Thus, the enum works as an easy white-list filter!

Since it's a white list of safe values, you can output that string directly if you want. It's safe and easy.

The other cool thing is IFTI. By providing a default value to request() of type Color, it knows to instantiate the whole thing as Color!

D's reflection also gives you all the available options with ease, which web.d uses to automatically create drop down lists in forms calling functions that take enums.

Way cool.

Note: you can also just use to!enum("string") directly if you want it to throw on invalid input instead of returning a default value.