how to make new C return other static type than C
deed
none at none.none
Sun Dec 9 12:02:11 PST 2012
Thanks for your replies. How about this:
interface I {}
interface I1 : I
{
void setx(int x);
int getx();
int getSum();
}
interface I2 : I
{
void sety(int y);
int gety();
int getSum();
}
class Impl : I1, I2
{
int x, y;
void setx(int x) { this.x = x; }
int getx() { return x; }
void sety(int y) { this.y = y; }
int gety() { return y; }
int getSum() { return x + y; }
}
class C
{
I1 i1;
I2 i2;
I currentInterface;
this()
{
i1 = new Impl; // static type I1
i2 = csat(I2)i1; // try to refer to same object through
i2
currentInterface = i1;
}
void switchInterface() // Could be private and called
depending on
// internal state
{
if (currentInterface == i1) { currentInterface = i2; }
else { currentInterface = i1; }
}
/* Direct all method calls to the current interface...
Perhaps opDispatch?
*/
}
void main()
{
auto c = new C;
c.setx(5); // Should set x to 5 through i1
c.getSum(); // Should return 5. (5 + 0)
c.sety(3); // Should not be possible
c.switchInterface() // currentInterface is now i2
c.setx(10); // Should not be possible
c.sety(3); // Should set y to 8 through i2
c.getSum(); // Should return 8. (5 + 3)
}
- Could this be possible?
- Will i1 and i2 expose different interfaces to the same object?
- How can a method call on an object be directed to an internal
object/interface?
More information about the Digitalmars-d-learn
mailing list