How to get a module with different type for code reuse?

∥☆過路亽.° 提交于 2019-12-12 04:21:15

问题


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:


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



来源:https://stackoverflow.com/questions/44860277/how-to-get-a-module-with-different-type-for-code-reuse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!