Paired real, complex derived types

Hi folks –

First post on the forum. A long time ago I was a frequent poster on comp.lang.fortran; it’s great to see many regulars from there are now active here!

I’m working on a project where many code paths are duplicated for real and complex numbers. This is easily handled using interface overloading for procedures; but to handle derived types, I’ve come up with a solution of “paired types”, where each real-based version of a type has a corresponding complex version.

To avoid too much code duplication, I use the fypp preprocessor (thanks, Aradi!). So, for instance, real and complex versions of the “foo” type (foo_rt and foo_ct) are declared thus:

#:for type, suffix in zip(('real', complex'), ('r', 's'))
type :: foo_${suffix}$t
  ${type}$ :: a
contains
  procedure :: do_stuff_${suffix}$
end type foo_${suffix}$t
#:endfor

I’m posting this approach to see if:

  • There is a formal name for this type pairing
  • Whether there is any existing literature
  • What other solutions folks with similar use-cases have come up with
  • To confirm that this can’t be done with parameterized derived types

Best wishes,

Rich

(edited to fix bugs in sample code)

Welcome, Rich, to the forum :slight_smile:

The approach you sketch is an example of generic programming. There is a working group that is trying to formalise this for Fortran, and many other languages allow this style already. It is quite tricky, actually, to fit it into the language without introducing ambiguities and unwanted impossibilities.

Welcome to the forum @rhtownsend .

What you show is essentially templates. The Generics Subgroup of the standards committee (including myself) are working on adding templates to the Fortran language properly. The syntax and semantics will be a bit more “Fortranic” than the use fypp, but is squarely aimed at supporting these kinds of use cases. If you want more info we’ve given plenty of presentations on it.