如何在Fortran中获取变量的唯一类型名称?
在Fortran中获取变量的唯一类型标识
Fortran标准中没有直接返回类型名称字符串的通用内置函数,但从Fortran 2008开始,有内置函数可以满足大部分场景需求,同时也可以通过自定义实现获取唯一类型标识(字符串或整数)。
1. 使用TYPE_NAME内置函数(Fortran 2008+)
TYPE_NAME是Fortran 2008引入的内置函数,配合CLASS(*)类型哑元使用,可返回变量的类型名称字符串:
program test_type_name implicit none type :: some integer :: val end type some real :: a type(some) :: x integer :: i print *, type_name(a) ! 输出 "real"(GCC)或 "REAL"(Intel,大小写依编译器而定) print *, type_name(x) ! 输出 "some" 或 "SOME" print *, type_name(i) ! 输出 "integer" 或 "INTEGER" end program test_type_name
- 对于内置类型(real、integer等),返回标准类型名;对于自定义派生类型,返回你定义的类型名。不同编译器返回的字符串大小写可能有差异,但均能准确对应类型。
2. 自定义实现唯一整数标识
如果需要兼容更早的Fortran标准,或需要可控的唯一整数标识,可通过SELECT TYPE结构实现自定义函数:
program test_custom_type_id implicit none type :: some integer :: val end type some real :: a type(some) :: x integer :: i print *, get_type_id(a) ! 返回1(对应real) print *, get_type_id(x) ! 返回2(对应some) print *, get_type_id(i) ! 返回3(对应integer) contains integer function get_type_id(var) result(id) class(*), intent(in) :: var select type(var) type is (real) id = 1 type is (integer) id = 3 type is (some) id = 2 class default id = -1 ! 未知类型标记 end select end function get_type_id end program test_custom_type_id
- 这种方式可灵活定义每个类型对应的唯一整数,需要手动维护所有需要识别的类型。
3. 使用TYPE函数判断类型唯一性
如果仅需要判断两个变量是否为同一类型,而非获取名称,Fortran 90+的TYPE函数可返回编译器内部的唯一整数标识,同一编译器下同一类型的标识完全一致:
program test_type_compare implicit none type :: some integer :: val end type some real :: a, b type(some) :: x, y print *, type(a) == type(b) ! 输出.TRUE. print *, type(x) == type(y) ! 输出.TRUE. print *, type(a) == type(x) ! 输出.FALSE. end program test_type_compare
- 该返回值仅用于类型比较,无法直接映射到类型名称,但满足“唯一标识”的需求。
内容的提问来源于stack exchange,提问作者hengyue li
相关产品推荐
相关产品推荐

