Using the Fortran preprocessor

Ok, so I can use something in a way it shouldn't, but here's my problem. I am trying to create an array that can contain different types that extend the same parent type. For this (via this post https://software.intel.com/en-us/forums/topic/280765 ) it is suggested to do it as follows.

program main

implicit none

type shape
    integer :: x,y
end type shape

type shape_c
    class(shape), pointer :: s
end type shape_c

type, extends(shape) :: rectangle
    integer :: w,h
end type rectangle

type, extends(shape) :: circle
    integer :: r
end type

type(rectangle) :: r
type(circle) :: c
type(shape) :: s

class(shape_c), dimension(:), allocatable :: shapes

r = initRect()
c = initCircle()
s = initShape()

allocate(shapes(3))

shapes(1)%s => r
shapes(2)%s => c
shapes(3)%s => s

write(*,*) shapes(1)%s%x * shapes(2)%s%x * shapes(3)%s%x

end program main

      

At the end of this post, someone suggests that I am using fpp to avoid having to write "% s" after the shapes every time. So I tried to use the below main program.

#define shapes(m) shapes(m)%s

      

This works great, of course, except for the "allocate (shapes (3))" case, which splits the code. I don't understand how to avoid this.

So, you might wonder if there is a better way to make an array of inherited variables, a way to avoid breaking during the allocate statement, or another solution to this problem. Also, a tutorial on how to use fpp will be helpful. https://software.intel.com/en-us/node/510271 is what I'm currently using and I'm sure it's helpful if I've used preprocessors before, but not so useful to someone did not.

I am using Intel Visual Fortran 2015 and VS2012.

+3


source to share


1 answer


Both shapes(m)

and shapes(m)%s

make sense in Fortran, so overriding all shapes(m)

as shapes(m)%s

clearly breaks the code. You should use the non-Fortran keyword when defining a macro, or at least use a word that is missing elsewhere. For example,

#define SHAPES(m) shapes(m)%s

      



(usually a cap with preprocessor macros) or something shorter if you insist on saving keystrokes. At the same time, using a preprocessor to shorten the code is perhaps not the best style and may impair readability. I suggest using your text editor to easily insert the appropriate bits of code.

0


source







All Articles