【发布时间】:2013-12-07 01:34:21
【问题描述】:
我正在尝试将interfaced 过程定义为 Fortran type 定义中的类型绑定过程,但它似乎不像预期的那样工作。考虑以下模块:
module example_module
implicit none
private
interface add_them
module procedure add_them_integer,add_them_real
end interface add_them
type, public :: foo
integer, private :: a=1,b=2
real, private :: c=4.,d=5.
contains
procedure, public :: add => add_them
end type foo
contains
subroutine add_them_integer(self,x)
class(foo), intent(in) :: self
integer, intent(in) :: x
print *,self%a+self%b+x
end subroutine add_them_integer
subroutine add_them_real(self,x)
class(foo), intent(in) :: self
real, intent(in) :: x
print *,self%c+self%d+x
end subroutine add_them_real
end module example_module
以及使用该模块的相应程序:
program example
use example_module
implicit none
type(foo) :: foofoo
call foofoo%add(1)
call foofoo%add(2.)
end program example
我希望它可以编译,结果应该是 4 和 11。但是,gfortran 报告以下错误:
procedure, public :: add => add_them
1
Error: 'add_them' must be a module procedure or an external procedure with an explicit interface at (1)
一种解决方法是使用generic 类型绑定过程而不是interfaced 一个,因此模块如下:
module example_module
implicit none
private
type, public :: foo
integer, private :: a=1,b=2
real, private :: c=4.,d=5.
contains
generic, public :: add => add_them_integer,add_them_real
procedure, private :: add_them_integer,add_them_real
end type foo
contains
subroutine add_them_integer(self,x)
class(foo), intent(in) :: self
integer, intent(in) :: x
print *,self%a+self%b+x
end subroutine add_them_integer
subroutine add_them_real(self,x)
class(foo), intent(in) :: self
real, intent(in) :: x
print *,self%c+self%d+x
end subroutine add_them_real
end module example_module
这按预期工作。但是,我不能使用generic 过程。以上只是演示问题的简化示例,但在我的实际代码中,“add_them”不能是generic 过程,因为“foo”实际上是派生类型,而“add_them”覆盖了父类型中定义的过程; gfortran(至少)不允许generic 过程覆盖基本过程。为了绕过这个限制,我想我应该改用interface,但是正如你在上面的例子中看到的,虽然'add_them'定义正确,编译器抱怨“'add_them'必须是模块过程或外部过程具有显式接口”。
任何帮助将不胜感激;提前致谢。
【问题讨论】:
标签: interface fortran type-bounds