有没有办法有条件地设置公共数据结构的类型?
有没有办法有条件地设置公共数据结构?
例如:
MODULE EXAMPLE
USE DATA_TYPE_Define, ONLY: DATA_TYPE_A, DATA_TYPE_B
USE PARAMETER, ONLY: CaseAisTrue
! Disable all implicit typing
IMPLICIT NONE
! ------------
! Visibilities
! ------------
! Everything private by default
PRIVATE
! The shared data
PUBLIC :: DATA
! ------------------------------------------------
! The shared data
! ------------------------------------------------
IF (CaseAisTrue) Then
TYPE(DATA_TYPE_A), SAVE :: DATA
ELSE
TYPE(DATA_TYPE_B), SAVE :: DATA
END IF
CONTAINS
...
data_type_a和data_type_b是两个不同的数据结构/派生类型。
除了引入更多的公共变量外,还有什么好方法可以设置它吗?
谢谢你!
Is there a way to conditionally set a public data structure?
For example:
MODULE EXAMPLE
USE DATA_TYPE_Define, ONLY: DATA_TYPE_A, DATA_TYPE_B
USE PARAMETER, ONLY: CaseAisTrue
! Disable all implicit typing
IMPLICIT NONE
! ------------
! Visibilities
! ------------
! Everything private by default
PRIVATE
! The shared data
PUBLIC :: DATA
! ------------------------------------------------
! The shared data
! ------------------------------------------------
IF (CaseAisTrue) Then
TYPE(DATA_TYPE_A), SAVE :: DATA
ELSE
TYPE(DATA_TYPE_B), SAVE :: DATA
END IF
CONTAINS
...
Where DATA_TYPE_A and DATA_TYPE_B are two different data structures/derived types.
Is there any good way to set this up besides introducing more public variables?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(1)
我看到了两个选项。
data
以后在代码中的其他任何地方访问相同的唯一原因是因为data_type_a
和data_type_b
基本上具有相同的API 。这是一个典型的示例面向对象的编程模式:您希望两种数据类型共享相同的API:如果您需要在要访问的数据类型之间继续切换,则可以为它们提供两个单独的变量:
并指向它们使用指针:
否则,如果您不经常更改它,则可以使用多态分配,这将更加优雅:
并在需要时分配正确的类型:
parameter
> ized)编译时间?然后,编译器预处理器将是最有用的。例如,使用C前处理器,您将拥有:后一个选项是在编译之前执行的,即,该数据类型已执行,无法更改。
I see two options.
DATA
anywhere else in the code later is becauseDATA_TYPE_A
andDATA_TYPE_B
have essentially the same API. This is a typical example object-oriented programming pattern: you want the two data types share the same API:If you need to keep switching between the data types you're accessing, you can have two separate variables for them:
And point to them using a pointer:
Otherwise, if you don't change it that often, you could just use polymorphic allocation, that would be more elegant:
And allocate the right type whenever needed:
parameter
ized) at compile time? Then, a compiler pre-processor will be most useful. For example, with the C pre-processor, you'd have:This latter option is performed before compilation, i.e., that datatype is enforced and can never be changed.