简体   繁体   中英

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

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM