Some questions concerning procedure overloading in Fortran

Hi all,

I’m working on a personal numerical libray in Fortran. I want to overload my functions so that they can be called with arguments of any numeric type. I have several questions about this.

As an example, assume a function with two arguments that can be integer or real: fcn(arg1,arg2). The possible ways to call this function would be fcn(real,real), fcn(real,int), fcn(int,real), fcn(int,int).

  1. Do I have to rewrite my function (or write a shell) for every possible combination of argument types? With increasing number of arguments, the number of functions to be written would grow rapidly. Is there a better way to do this?

  2. Say I define an interface for these four functions above. What if my second argument is optional? Say the function would be called with only the first argument which is a real, the compiler would not know how to to choose between the fcn(real,real) and fcn(real,int) versions.

  3. What if I want the function return value to be with the same precision (i.e the same kind parameter) as the input (or say the input with the highest precision)? Do I have to overload my function for that as well?

Thanks in advance for any advice.

Best,
Maarten

Hi Maarten,

  1. Do I have to rewrite my function (or write a shell) for every possible combination of argument types?

Generic interfaces allow you to create a single generic name that can be used by callers. The generic name will then be mapped to an actual routine having the same signature. Each routine does need to have it’s own implementation. This does not mean that you need to have a routine for every possible combination, but you do need an implementation for the routines you wish to support.

Is there a better way to do this?

A non-standard method would be to use the IGNORE_TKR directive. The directive can be used to have the compiler ignore the Type, Kind, and/or Rank of one or more of your arguments. This will allow you to have procedures that handle multiple signatures. Most major compiler vendors support this directive but you do run risk of now having non-standard code. Please see page 165 of the PGI Compiler Reference Guide for details, (http://www.pgroup.com/doc/pgiref.pdf)

What if my second argument is optional?

Optional arguments are fine so long as they are the final arguments and the non-optional arguments are unique.

the compiler would not know how to to choose between the fcn(real,real) and fcn(real,int) versions.

Correct. This case would be illegal since both function’s signature would be the same and the compiler can’t tell them apart.

  1. What if I want the function return value to be with the same precision (i.e the same kind parameter) as the input (or say the input with the highest precision)? Do I have to overload my function for that as well?

The kind is part of the signature so if the input’s kind changes, then you would need to overload (unless you use IGNORE_TKR).

  • Mat