fortran - Fortran 中的通用映射函数

标签 fortran polymorphism

我的最终目标是在 Fortran 中有一个通用的映射函数,即一个接受任意类型 A 的数组和一个 A->B 类型的函数的函数,将此函数应用于给定数组的所有元素并返回一个B 类型的数组。我无法用数组实现它,所以我决定只从一个元素开始,但即使这样也行不通。

这是我的尝试:

program main
  integer :: elem_int
  elem_int = 1
  elem_int = to_int(apply_func(elem_int, add_one_int))
  print *, elem_int

contains
  ! don't know any other way to cast class(*) to int
  function to_int(unbound) result(res) 
    class(*), intent(in) :: unbound
    integer :: res
    select type (unbound)
      type is (integer)
        res = unbound
    end select
  end function

  function apply_func(elem, func) result(new_elem)
    class(*) :: elem
    class(*) :: func
    class(*), allocatable :: new_elem
    ! not sure if this allocation is needed
    allocate(new_elem, source = elem) 
    new_elem = func(elem)
  end function

  function add_one_int(num) result(res)
    integer :: num
    integer :: res
    res = num + 1
  end function
end program

这段代码可以编译,但由于行中的段错误而崩溃

new_elem = func(elem)

我想也许它认为 func 是一个数组并试图索引它所以我尝试像这样定义抽象接口(interface):

  abstract interface
    function any_func(x)
      class(*) :: x
      class(*), allocatable :: any_func
    end function
  end interface

并将 func 的声明更改为 procedure(any_func),但随后我的编译器 (ifort 18.0.1) 产生以下错误:

error #7069:关联的实际函数结果的特征与虚拟函数结果的特征不同。 [ADD_ONE_INT]

我想要一个任何 1-arg 函数都符合它的接口(interface),但是,显然,这不是声明它的正确方法。有什么想法可以在工作的同时做到这一点吗?提前致谢。

最佳答案

经过一些挖掘,我了解到当一个函数被标记为 elemental 时,它可以应用于一个数组,基本上提供了我一直在寻找的相同功能。这是一个 int->real 类型的函数示例

program main
  integer :: int_arr(3)
  real :: real_arr(3)
  int_arr = [1, 2, 3]
  real_arr = my_sqrt(int_arr)
  print *, real_arr
contains
  elemental function my_sqrt(arg) result(res)
    integer, intent(in) :: arg
    real :: res
    res = sqrt(real(arg))
  end function
end program

关于fortran - Fortran 中的通用映射函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53908589/

相关文章:

fortran - gfortran 不编译实变量

C++ 编译时多态性

java - List<Dog> 是 List<Animal> 的子类吗?为什么 Java 泛型不是隐式多态的?

c# - 如何使用多态避免 'If cascade' 和类型转换?

用于任意长度字符串的 Fortran 函数

arrays - 在 Fortran 中,传递 myArray 或 myArray( :) to a function?

fortran - 使用 g77 编译 Fortran 时遇到问题

arrays - Fortran 没有给出数组分配错误

oop - 使用泛型参数覆盖Dart方法

c++ - 多态问题C++