Is it possible to store properties via opDispatch using tuples?
H. S. Teoh
hsteoh at quickfur.ath.cx
Fri Jan 17 11:18:30 PST 2014
On Fri, Jan 17, 2014 at 06:49:25PM +0000, Gary Willoughby wrote:
[...]
> 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.
Is it possible, at compile-time, to determine the type just from the
property name alone? If not (i.e., different class instances may have a
property named "abc" map to int or string, respectively), then this is
not possible, because the return type of opDispatch can only depend on
its compile-time parameter, that is, the property name.
If there's a compile-time procedure for determining the type of a
property solely from its name, then yes, this is possible. What you do
is to first determine the return type from the property name (at
compile-time!), hash the .mangleof of this type, and store an AA of AA's
of property values, with the outer AA keyed by the hash value.
Something like this:
class MyClass {
Variant[string][size_t] props;
auto opDispatch(string ident)() {
alias returnType = ... /* determine type from ident */;
enum id = hashOf(T.mangleof); // unique ID for T
return cast(returnType)props[id][ident];
}
}
The success of this depends on whether it's possible to determine the
return type from the property name (at compile-time), though. If that's
not possible, then this doesn't work.
T
--
Acid falls with the rain; with love comes the pain.
More information about the Digitalmars-d-learn
mailing list