Interface problems

Dmitry Olshansky dmitry.olsh at gmail.com
Wed Jan 26 02:12:39 PST 2011


On 26.01.2011 8:12, Mandeep Singh Brar wrote:
> Mandeep Singh Brar:
>
>> I am not able to:
>>
>> - find indexOf interface in an interface range using std.algorithm.
>> I don't understand. Please explain better.
> In the following snippet:
>       Interface interfaceA{}
>       class C:interfaceA{}
>       class D:interfaceA{}
>
>       interfaceA[] registry;
>       register(interfaceA a) { registry ~= a; }
>       unregister(interfaceA a) {idx = registry.indexOf(a); registry.replace(idx,
> idx+1, null); }
> In the above statement indexOf does not work.
>

You should use 'is' for such kind of thing. The problem is that == uses 
opEquals or opCmp, there is no such thing for interfaces AFIKT. But for 
every pointer like type we can check if they are the same with 'is'. 
Here is your fixed snippet :

import std.algorithm;
import std.array;

interface interfaceA{}
      class C:interfaceA{}
      class D:interfaceA{}

      interfaceA[] registry;
      void register(interfaceA a) { registry ~= a; }
      void unregister(interfaceA a) {
     auto idx = indexOf!"a is b"(registry,a);
     registry.replace(idx,idx+1, null);

     }
void main(){
     auto b = new D();
     register(new C());
     register(b);
     unregister(b);
}


>> - compare interface objects
Yeah, here it sucks. 'is' is your best chance ;)
>> What kind of comparisons do you need to perform and why?
> Simple comparisons like in the below snippet
>        class A {
>            interfaceTest myInstance;
>            setInstance(interfaceTest interfaceInstance) {
>                   if(myInstance != interfaceInstance) //does not work
>                   {
>                        updateMyInstance;
>                        doStuff;
>                   }
>            }
>        }
>
>
Here just use '!is ' instead of !=

[snip]

>        Just store various types of objects in a generic way like
>             Object[] objects;
>             objects ~= objA; objects~= interB and so on.
>
>        I cant use Variant because interface can not be assigned to Variants and i
> cant use Objects too.
>

If you need to pile up different interfaces (no occasional Object ). The 
workaround would be to inherit all your interfaces from
a common base like:

interface Base{}
interface A: Base{...}
interface B: Base{...}
class CA: A{.. }
Base[] pile;
pile ~= new CA();
>> Bye,
>> bearophile
> Thanks
> Mandeep


-- 
Dmitry Olshansky



More information about the Digitalmars-d-learn mailing list