On Sunday, June 04, 2017 22:52:55 Mike B Johnson via Digitalmars-d-learn wrote: > I am dealing with some COM stuff and some functions use VARIANT, > which can hold an enum. > > Instead of having to manually convert the enum(and for that > matter, other things) to VARIANT, is it possible to have them > automatically converted? > > This is because an enum is always convertible to a VARIANT but > not the other way around. So, when a enum is passed to a function > accepting a VARIANT, it should just work. Overloading is not an > option.
Aside from whatever implicit conversions are built into the language, the only way to define an implicit conversion in D is via alias this on a user-defined type, which then tells that type that it can convert to whatever type the result of the alias this is. e.g. if you have struct S { int x; alias x this; } then S can implicitly convert to int, and when it does, the value of x is used (alternatively, a member function could be used, in which case, the result of the member function would be used as the result of the conversion). So, that allows you to tell how to convert a type _to_ another type, but it does not allow you to convert _from_ another type. So, if you're implicitly converting from type A to type B, it will work if type A has been told how to convert to B, but there is no way for B to say that an A can be converted to a B. Only A can define the conversion. So, if you have control of the definition of the base type of the enum, then you can define an alias this on it to convert to a VARIANT, but if you don't have control over the definition of the base type of the enum (e.g. if it's int, as is the default), then you're out of luck. And if you're dealing with COM, then I'm guessing that your enum has a base type of int, and you obviously don't control the definition of int, so you can't add an alias this to it. So, if you can't change the enum, and you can't change the function that you're calling, then you'll have to insert something in between - be it a conversion function, an explicit construction of VARIANT with the enum, or some kind of wrapper function around the one that you're calling. But unless the enum itself knows how to implicitly convert to a VARIANT thanks to alias this, there is no implicit conversion. std.typecons.Nullable has this sort of problem, which has historically forced folks to do stuff like Nullable!int(42) when passing the actual type to a function that accepts a Nullable wrapper around the type, which is pretty annoying. Recently, a nullable function was added to std.typecons which uses IFTI to infer the type of the Nullable auto nullable(T)(T t) { return Nullable!T(t); } and then you could pass nullable(42) instead of Nullable!int(42), so it's more user-friendly, but it still requires an explicit conversion unless you overload the function. It's a downside to D's stricter approach to implicit conversions. - Jonathan M Davis