Fortran 2008中的函数重载

Een*_*oku 5 polymorphism fortran overloading fortran2008

我从Fortran 2008开始,我正在努力与OOP大力合作.看来,很少有材料可以解释2008语言标准中非常基本的OOP概念.

我找到了有关继承的信息,但我无法找到有关多态的任何信息.

所以,如果我想在C++中重载一个函数,我可以这样做(来自维基百科的例子):

// volume of a cube
int volume(const int s)
{
    return s*s*s;
}

// volume of a cylinder
double volume(const double r, const int h)
{
    return 3.1415926*r*r*static_cast<double>(h);
}

// volume of a cuboid
long volume(const long l, const int b, const int h)
{
    return l*b*h;
}
Run Code Online (Sandbox Code Playgroud)

但是,我怎么能在Fortran 2008中做同样的事情呢?

fra*_*lus 4

C++ 示例中给出的重载思想在 Fortran 中有一个实现,可以追溯到Fortran 90 的泛型。

给定一组特定过程,可以使用通用标识符来识别该组。在这个答案中,我将对这个概念进行非常高层次的介绍。有很多微妙之处可能需要进一步阅读/解决问题。

与 C++ 示例不同,我们的 Fortran 特定过程需要单独命名。让我们有两个函数(第三个可以比照添加)

integer function volume_cube(s)
  integer, intent(in) :: s
  ...
end function volume_cube

double precision function volume_cylinder(r, h)
  double precision, intent(in) :: r
  integer, intent(in) :: h
  ...
end function volume_cylinder
Run Code Online (Sandbox Code Playgroud)

然后我们可以添加一个通用接口volume

interface volume
  procedure volume_cube, volume_cylinder
end interface
Run Code Online (Sandbox Code Playgroud)

然后我们可以引用泛型volume,编译器将确定要使用哪个特定函数。

关于泛型还有很多东西需要了解,包括除了简单的重载之外它们还提供什么。人们还应该了解具体程序是如何解决的(在这种情况下很简单,在其他情况下则不然)以及对哪些具体程序可以混为一谈的限制。当您使用泛型时,有问题的案例可能会有特定的问题。我在这里回答只是因为我看不到介绍性问题,并且我不尝试解决许多不同的困难或价值观。


完整示例

module mod

  private

  interface volume
     module procedure volume_cube, volume_cylinder
  end interface volume
  public volume

contains
  integer function volume_cube(s)
    integer, intent(in) :: s
    volume_cube = s**3
  end function volume_cube

  double precision function volume_cylinder(r, h)
    double precision, intent(in) :: r
    integer, intent(in) :: h
    volume_cylinder = 3.1415926d0*r**2*h
  end function volume_cylinder

end module mod

  use mod

  print*, volume(2), volume(2d0,4)
end
Run Code Online (Sandbox Code Playgroud)