How to get a module with different type for code r

2019-08-30 09:13发布

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.

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?

1条回答
Evening l夕情丶
2楼-- · 2019-08-30 09:20

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).

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

included in

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

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

查看更多
登录 后发表回答