fortran66のブログ

fortran について書きます。

Fortran 2018 : スカラーと配列両受け

unlimited type (*), assumed shape (..)

unlimited polymorphic class ; class(*) のみならず、unlimited polymorphic type ; type(*) もあることに気づきませんでした。

これを assumed shape の仮引数として使うことで、実引数として任意型のスカラー変数、定数、配列を取ることが出来ます。class(*) でもできますが・・・

そうした上で select type, select rank (F2018) で振り分けて、その先の処理ができます。
[追記 R1.5.31:type(*) では select type を利用できないそうです。type(*) は C 言語との連携目的で void * 型用に導入されたもので型情報を持たないようです。 ]


ソース・プログラム

module m_test
    implicit none
contains
    subroutine test(x)
    type(*), intent(in) :: x(..)
    print *, 'rank', rank(x), ': shape', shape(x) 
    end subroutine 
end module m_test
    
program main
    use m_test
    implicit none
    real :: a, b(10), bb(3, 3)
    integer :: i, m(10)
    complex :: c, d(5)
    character(5) :: txt
    call test([1, 2, 3, 4, 5])
    call test(a)
    call test(b)
    call test(bb)
    call test(c)
    call test(d)
    call test(txt)
end program main

実行結果

 rank           1 : shape           5
 rank           0 : shape
 rank           1 : shape          10
 rank           2 : shape           3           3
 rank           0 : shape
 rank           1 : shape           5
 rank           0 : shape
続行するには何かキーを押してください . . .

Modern Fortran Explained: Incorporating Fortran 2018 (Numerical Mathematics and Scientific Computation)

Modern Fortran Explained: Incorporating Fortran 2018 (Numerical Mathematics and Scientific Computation)