dimanche 5 novembre 2017

Find out from an object as an interface whose instance it is

I have the following scenario (http://ift.tt/2zfHnBJ):

import std.stdio;

void main(string[] args)
{
    inter1 c1 = new foo();
    foo c2 = new foo();
    writeln("Origin=interface: ", typeof(c1).stringof);
    writeln("Origin=class: ", typeof(c2).stringof);
}

interface inter1 {
}

class foo : inter1 {
}

I work with interfaces and have different implementations for them. Now I need to know which concrete implementation is currently being used. So in the example above, I would like to know from c1 that it is an instance of the class foo.

Is this possible in the language D?

I have already tried the possibilities of object (e.g. TypeInfo_Class) and std.traits. Unfortunately without success.

A workaround is, of course, to provide the interface with a suitable meta method (http://ift.tt/2heg2ZY):

import std.stdio;

void main(string[] args)
{
    inter1 c1 = new foo();
    foo c2 = new foo();
    writeln("Origin=interface: ", c1.strategyName);
    writeln("Origin=class: ", c2.strategyName);
}

interface inter1 {
    @property string strategyName() const;
}

class foo : inter1 {
    @property string strategyName() const {
        return "foo";
    }
}

However, this is cumbersome and unusual for D. I can well imagine that there is a better implementation of this.

Best regards

Thorsten





Aucun commentaire:

Enregistrer un commentaire