Search code examples
generic-programmingeiffel

Eiffel: Is there a way to test a given Generic parameter of a Class without any attached instance of it?


Is there a way to test a given Generic parameter of a Class without any attached instance of it?

class BAG[G -> MOUSE]

feature -- 

    discriminate
        do
            if G.conforms_to (MAMMAL) then
                io.putstring ("you gave me a real animal")
            elseif G.conforms_to (COMPUTER_ACCESSORY) then
                io.putstring ("Seems you don't like animals such as computers")
            else
                io.pustring ("Still dont know what you are dealing with")
            end
        end

Solution

  • You've almost nailed it. The missing part is curly braces and parentheses:

            if ({G}).conforms_to ({MAMMAL}) then
                io.put_string ("You gave me a real animal.")
            elseif ({G}).conforms_to ({COMPUTER_ACCESSORY}) then
                io.put_string ("Seems you don't like animals such as computers.")
            else
                io.put_string ("Still don't know what you are dealing with.")
            end
    

    Explanation:

    1. {FOO}, where FOO is a type name, stands for a type object. It works for any type, including formal generics, thus {G} and {MAMMAL}.
    2. The syntax {FOO}.bar is reserved for non-object calls. But here we want an object call on the type object. Therefore, {G} is enclosed in parentheses: ({G}).conforms_to (instead of {G}.conforms_to).