如何获得具有不同类型的模块以进行代码重用? [英] How to get a module with different type for code reuse?

查看:88
本文介绍了如何获得具有不同类型的模块以进行代码重用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有两个模块.这两个模块中的功能完全相同,但是其中一个功能完全是关于处理实类型的,而另一个功能是关于复杂类型的.所有这些模块将在一个程序中使用,因此根据不同的参数输入,我们需要选择不同的模块.

Now I have two modules. The functions in the two modules are exactly the same, but one is all about coping with real type, while another is about complex type. All these modules will be used in one program, thus according to different parameter input, we need to choose different modules.

根据代码重用"的主要精神,如何使这些模块成为一个代码副本.这些模块要求高性能(因此需要避免使用"if","select"之类的东西).我想知道我们有什么解决办法吗?

According to the major spirit of "code reuse", how to make these modules into one copy of code. And these modules require high performances(thus one need to avoid to use something like "if", "select"). I wonder if we have any solution?

推荐答案

这是下一个(2020?)Fortran标准的争论话题.无法在当前版本中参数化Fortran模块.许多人都认为它是一个很大的缺陷(请参见comp.lang.fortran上的讨论).

This is a topic of debate for the next (2020?) Fortran standard. It is not possible to parametrize a Fortran module in current versions. And it is perceived by many as big defect (see discussions at comp.lang.fortran).

您可以做的是使用预处理器(通常是C预处理器)并包含文件.您可以在包含文件中将类型定义为宏名称

What you can do is to use a preprocessor (most often the C preprocessor) and include files. You define the type as a macro name in the include file

  MYTYPE :: x

然后添加具有适当定义的文件

then you include the file with an appropriate definition

#define MYTYPE real
#include "module-template.F90"
#undef MYTYPE

#define MYTYPE complex
#include "module-template.F90"
#undef MYTYPE

您通过以下方式启用前处理器

You enable the preprocesor by

 gfortran -cpp
 ifort -fpp

以及类似内容(请参见编译器的手册).

and similar (see the manual of your compiler).

在包含文件中可以看到一个示例(由我编写)

An example (written by me) can be seen in include file

https://github.com/LadaF/PoisFFT /blob/master/src/fft-inc.f90

包含在

https://github.com/LadaF/PoisFFT/blob /master/src/fft.f90

如您在示例中看到的那样,其中有一些要点.您需要两个模块具有不同的名称,例如mod_realmod_complex.您可以与示例类似地执行此操作,也可以使用宏分类来生成模块名称.请参阅 C预处理程序宏:串联(例如Fortan90的示例)使用gfortran在宏中连接字符串

As you can see in the examples there are some fine points in it. You need the two modules to have different names, like mod_real and mod_complex. You can do that similarly to the examples or you can use macro catenation to generate the module name. See C preprocessor macro: concatenation (example for Fortan90) and Concatenate strings in a macro using gfortran

这篇关于如何获得具有不同类型的模块以进行代码重用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆