Using a derived type pointer and a polymorphic tar

2019-08-08 02:48发布

问题:

The Fortran function listed below compiles and executes as expected using ifort 11.1. However GFortran 4.6 returns the compiler error:

THIS_NML => THIS
Error: Different types in pointer assignment at (1); attempted assignment of CLASS(UNIT) to TYPE(UNIT).

Fortran code:

FUNCTION PROCESS_COMMAND(THIS, CMD, DATA) RESULT(RET)
   CLASS(UNIT), INTENT(INOUT), TARGET :: THIS
   CHARACTER(LEN = *), INTENT(IN)     :: CMD
   CHARACTER(LEN = *), INTENT(IN)     :: DATA
   CHARACTER(LEN = 200)               :: STRING
   INTEGER                            :: IOS
   TYPE(UNIT), POINTER                :: THIS_NML

   ! CREATE A NAMELIST
   NAMELIST /VARS/ THIS_NML
   THIS_NML => THIS  
   RET = 0
   STRING = '&VARS THIS_NML%' // TRIM(CMD) // ' = ' // TRIM(DATA) // ' /'

   ! READ CMD AND DATA
   READ(STRING, NML=VARS, IOSTAT=IOS)
   RET = IOS

END FUNCTION PROCESS_COMMAND

Because namelist's cannot be created using polymorphic objects, the derived type pointer THIS_NML is being used to create the namelist. Any ideas how to make this work with GFortran?

回答1:

Try using select type construct. Something like

select type ( A => THIS )
   type is ( UNIT )
      Here you can treat A as nonpolymorphic variable of type UNIT (if the test is succesful).
end select