On Friday, 17 January 2014 at 17:50:54 UTC, H. S. Teoh wrote:
On Fri, Jan 17, 2014 at 05:29:14PM +0000, Gary Willoughby wrote:
On Friday, 17 January 2014 at 15:56:46 UTC, H. S. Teoh wrote:
>Couldn't you just return a Variant? I thought this is what >Variants
>are made for.
>
>
>T

Yes but then i would need to coerce it to get it's underlying type.

But isn't that what you'd have to do anyway? I mean, how else would the
following code work?

        class DynClass {
                ...
                auto opDispatch(string field)() {
                        return dotDotDotMagic();
                }
        }

        void main(string[] args) {
                auto d = new DynClass();
                if (args[1] == "int")
                        d.abc = 123; // d.abc = int
                else
                        d.abc = "xyz"; // d.abc = string

                // Suppose this somehow works:
                auto x = d.abc; // what's the type of x?
        }

Since the type of x must be known at compile-time, but the type of d.abc can't be known until runtime, the above code can't possibly work unless
d.abc returns a Variant. It's simply not possible for a
runtime-determined type to be put into a variable of compile-time
determined type without some kind of runtime check.

Now I'm not sure if Variant allows assignment to a static type, but in
theory this should be possible:

        // assume d.abc returns a Variant
int x = d.abc; // will assert if d.abc doesn't hold an int at runtime


T

In the example in my original post the types are known at compile time but they are different between properties. I wondered if there was a solution to storing and retrieving while preserving the original type via opDispatch.

I have a working solution but it only stores the base type. So i f i have an inheritance chain like this:

A -> B -> C

I can store properties of type A, B and C but when i retrieve them they all come back as A because of array covariance. I wonder if there is a way of casting them automagically to the correct type.

Reply via email to