Is it possible to store properties via opDispatch using tuples?
H. S. Teoh
hsteoh at quickfur.ath.cx
Fri Jan 17 11:28:55 PST 2014
On Fri, Jan 17, 2014 at 07:08:54PM +0000, Tobias Pankrath wrote:
> >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.
>
> So you basically want to declare a classmember for every name
> opDispatch is called with? That is not possible;
>
> I thought about declaring it static in opDispatch itself, but than
> you can only have one instance. Next thought: Declare a static
> hashmap and store the values there, but then you could just use
> std.variant.
One of the reasons this breaks down is because of situations like this:
class MyClass {
...
auto opDispatch(string op)() {
return ... /* assume we magically return the right type here */;
}
}
// Which of these assignments to 'abc' should determine its
// type? What if the function that gets called is determined at
// runtime only? What if they are in two separately-compiled
// modules?
void fun(MyClass o) {
o.abc = 123;
}
void gun(MyClass o) {
o.abc = "xyz";
}
auto x = o.abc; // what's the type of x?
Another problematic case:
auto o = new MyClass;
auto p = new MyClass;
o.abc = 123;
p.abc = "xyz";
// Problem: now the return type of opDispatch cannot be
// determined at compile-time.
Now, if you decide beforehand that "abc" is always an int, and "def" is
always a string, then this problem is avoided:
o.abc = 123; // OK
p.abc = 123; // OK
o.abc = "xyz"; // compile error
p.abc = "xyz"; // compile error
o.def = "xyz"; // OK
p.def = "xyz"; // OK
o.def = 123; // compile error
p.def = 123; // compile error
T
--
Freedom of speech: the whole world has no right *not* to hear my spouting off!
More information about the Digitalmars-d-learn
mailing list