On 05/19/2016 05:04 PM, chmike wrote:
interface AThing { ??? string name ??? }
class OneThing : AThing { ??? string name ??? "OneThing" ??? }
class OtherThing : AThing { ??? string name ??? "OtherThing" ??? }
void main()
{
// Accessing name as static information
writeln(OneThing.name ??? );
// Accessing name through polymorphism
AThing tbl;
tbl ~= new OneThing;
tbl ~= new OtherThing;
tbl ~= new OneThing;
foreach(a; tbl) writeln(a.name???);
}
The only viable solution I found so far is by using distinct member
names. In the interface we define name as a property, and in the class
we define the static member with another name. Is it possible to avoid
the different names ?
Here's what I could come up with. I wouldn't be surprised if there was a
simpler way to do it.
----
interface AThing
{
final string name() { return nameImpl(); }
string nameImpl();
}
class OneThing : AThing
{
static string name() { return "OneThing"; }
override string nameImpl() { return name(); }
}
class OtherThing : AThing
{
static string name() { return "OtherThing"; }
override string nameImpl() { return name(); }
}
void main()
{
import std.stdio;
// Accessing name as static information
writeln(OneThing.name);
// Accessing name through polymorphism
AThing[] tbl;
tbl ~= new OneThing;
tbl ~= new OtherThing;
tbl ~= new OneThing;
foreach(a; tbl) writeln(a.name);
}
----
Can use a mixin template to reduce the boilerplate:
----
interface AThing
{
final string name() { return nameImpl(); }
string nameImpl();
mixin template nameMixin()
{
static string name() { return typeof(this).stringof; }
override string nameImpl() { return name(); }
}
}
class OneThing : AThing { mixin AThing.nameMixin; }
class OtherThing : AThing { mixin AThing.nameMixin; }
----