【发布时间】:2015-10-02 08:00:12
【问题描述】:
有什么方法可以自动初始化一个常量的过程指针数组吗?
我有一堆例程,必须根据整数变量的值来调用它们。我不想使用select case 语句,而是想使用下面给出的过程指针。但是,如果我可以跳过过程指针数组的显式初始化,并将其定义为包装过程指针的常量数组,那就太好了。下面的代码演示了我找到的解决方案,注释行表示目标,我想实现:
module testmod
implicit none
abstract interface
subroutine subInterface()
end subroutine subInterface
end interface
type :: SubPtr
procedure(subInterface), nopass, pointer :: ptr
end type SubPtr
! Would be nice to use something like this:
!type(SubPtr), parameter :: subs(2) = [ SubPtr(sub1), SubPtr(sub2) ]
contains
subroutine sub1()
print *, "SUB1"
end subroutine sub1
subroutine sub2()
print *, "SUB2"
end subroutine sub2
end module testmod
program test
use testmod
implicit none
type(SubPtr) :: subs(2)
integer :: ii
! Would be nice to get rid of those two initialization lines
subs(1) = SubPtr(sub1)
subs(2) = SubPtr(sub2)
! Testing procedure pointer array
do ii = 1, 2
call subs(ii)%ptr()
end do
end program test
【问题讨论】:
-
通过将子例程放在不同的模块中,我能够消除大部分错误消息。尽管如此,Cray 编译器仍报告:
The initialization expression must be a constant to be used with PARAMETER assignment for object "SUBS".初始化指向这些子例程之一的独立过程指针效果很好。 -
初始化一个指向这些子例程之一的独立过程指针效果很好,但是对于
PARAMETR过程指针来说太疯狂了!对于编译器,在过程指针上下文中使用PARAMETER是一个语法错误,我没有时间检查标准中的约束,但可能不允许有常量过程指针并将它们初始化为现有的子例程.
标签: fortran fortran2003 fortran2008