To: J3 J3/18-116 From: Bill Long Subject: Templates Date: 2018-February-07 Discussion: ----------- As noted several times in WG5/N2147, programmers have long been frustrated with the prospect of generating almost identical code for multiple data types. This problem has been solved in languages like C++ with the use of templates. Such a feature would be welcome in Fortran and is frequently cited as the most obvious shortcoming of the language. Feature outline: ---------------- Fortran 2018 already has several features that could be extended to provide a template facility. By reusing existing features, the implementation and programmer learning burdens are reduced. The overall goal here is to make the feature intuitive, easy to use and understand, and easy to implement. Possibilities (references are to N2146): 1) We already have the concept of a prefix {elemental, impure, module, non_recursive, pure, and recursive} for the initial SUBROUTINE or FUNCTION statement of a subprogram. Add "template" to this list, which would make the subprogram a "template procedure". Constraint: A template procedure shall appear only in a module. {To ensure that a caller can find the template at compile time.} 2) For a template procedure, allow the following modifications for dummy arguments: a) Arguments declared TYPE(*) can be used as ordinary variables. b) Permit dummy arguments of intrinsic types to be declared assumed-kind (INTEGER(*), REAL(*), COMPLEX(*), LOGICAL(*), CHARACTER(KIND=*)). c) Add a new declaration "type" of NUMERIC to represent any of INTEGER, REAL, or COMPLEX, that can appear in expressions that involve arithmetic operations. d) Provide a mechanism for declaring a local variable with the same type and type parameters as one of the dummy arguments. {Useful for local temps and function result variables.} 3) Referencing a template procedure involves creation of a version of the procedure with the dummy arguments assuming the type and kind of the corresponding actual arguments to the extent allowed by the declaration of the dummy argument. Operations on the new dummy arguments are required to be appropriate for their assumed type and kind. {For example, if the dummy is an argument to an intrinsic procedure the effective type and kind shall be allowed for that intrinsic. Similarly, a complex effective argument shall not appear as an operand for a >, <, >=, or <= operator.} 4) The technology for generating internal mangled names for the created procedures, and for consolodaiting duplicates, can reuse much of what already exists for C++.