TrippLamb
TrippLamb

Reputation: 1619

Returning Polymorphic Class

I'm trying to understand why one of the below is allowed by the standard while the other is not. They don't seem different except for boilerplate code to me. I feel like I'm misunderstanding something, or that there is a better way of doing it. Any help would be appreciated.

Not allowed:

real :: x
class(*) :: temp

x = 4

temp = genericAssignment(x)

select type(temp)
type is(real)
    write(*,*) temp
end select

contains

function genericAssignment(a) result(b)
    class(*) :: a
    class(*) :: b

    allocate(b, source=a)
end function genericAssignment

Allowed:

Type GenericContainer
    class(*), pointer :: gen
End Type

real :: x
class(*) :: ptr
type(GenericContainer) :: temp

x = 4

temp = genericAssignment(x)

select type(ptr => temp%gen)
type is(real)
    write(*,*) ptr
end select

contains

function genericAssignment(a) result(b)
    class(*) :: a
    type(GenericContainer) :: b

    allocate(b%gen, source=a)
end function genericAssignment

Upvotes: 1

Views: 133

Answers (1)

IanH
IanH

Reputation: 21431

The current standard allows both.

The "allowed" code block has a function with a non-polymorphic result, with the result of evaluating the function being assigned to a non-polymorphic variable. This is valid Fortran 2003.

The "not allowed" block has a function with a polymorphic result, with the result of evaluating the function being assigned to a polymorphic variable. This is valid Fortran 2008.

Note that the number of complete Fortran 2008 compiler implementations out there is small.

~~~

The function in the "not allowed" block is somewhat pointless - the code block is equivalent to:

real :: x
class(*) :: temp

x = 4

temp = x

select type(temp)
type is(real)
  write(*,*) temp
end select

Upvotes: 2

Related Questions