User-defined operators in Fortran

2019-06-26 06:53发布

问题:

I had a question about the correct way of programming user-defined operators in Fortran. To be more specific, I will provide the example of my problem. I am working on creating a user-defined data type for spherical particles called 'Particle'. I want to define an operator that takes an existing array of Particle objects and adds a new Particle object to it. I was wondering how I would go about defining user defined operators to do such an action.

Currently I have, within the type definition for Particle, the following lines:

procedure, public:: addNewParticleTo
generic:: operator(.spawn.) => addNewParticleTo

Following which, I have a subroutine that is defined as follows:

subroutine addNewParticleTo(a_LHS, a_RHS)
  implicit none
  class(Particle), dimension(:), allocatable, intent(in):: a_LHS
  class(Particle), dimension(:), allocatable, intent(inout):: a_RHS
  <rest of the code>
end subroutine addNewParticleTo

I intend for the operator to be invoked as:

particle .spawn. particleArray

I was wondering if this is the correct way to go about doing this. Any suggestions or advise on this will be very helpful.

回答1:

To expand on the comments, you will need to have the operator code as a function. Further, each input would need to be intent(in). This would indeed allow something like array = particle .spawn. array.

However, another change is required to your subroutine: one of your arguments should be a scalar. [The first, unless you play with the pass attribute.]

function addNewParticleTo(A, B) result(C)
  class(particle), intent(in) :: A
  class(particle), allocatable, intent(in)  :: B(:)
  class(particle), allocatable :: C(:)
  ! ... code to do the appending
end function

Finally, my advice is that having this as a type-bound operator is making things quite complicated, with the polymorphism and so on. Also, array = particle .spawn. array seems very unintuitive.

Instead, just a plain subroutine so that call add_to_particle_array(all_particles, new_particle) works seems cleaner. This is closer to your original code, but doesn't answer your question about operators, alas.