我正在尝试编写一个过程,该过程存储用户数组的地址以供进一步处理.问题被封装在这个测试程序中:
program test_ptr
real(4), target, allocatable :: i4(:,:)
real(8), target, allocatable :: i8(:,:)
real(4), pointer :: p(:,:)
allocate(i4(2,2))
allocate(i8(2,2))
p => i4 ! ok
p => i8 ! compile error
end
Run Code Online (Sandbox Code Playgroud)
编译器建议为不同类型制作不同的指针.但我不想为real(4)和real(8)创建单独的指针.我试图制作通用和紧凑的解决方案,并有一个指针用于不同类型的数据.可能吗?
使用(无限制)多态性可以做到这一点p
.
program test_ptr
implicit none
real(kind(0.)), target :: r4(2,2)
real(kind(0d0)), target :: r8(2,2)
class(*), pointer :: p(:,:)
! some assignments, etc.
if (...some crazy condition...) then
p => r4
else
p => r8
end if
select type (p)
type is (real(kind(0.)))
print *, p
type is (real(kind(0d0)))
print *, p
end select
end program
Run Code Online (Sandbox Code Playgroud)
select type
以后使用时要特别注意p
.