You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The Fortran-lang stdlib defines a function optval that can be used to define provide a fallback value for an optional argument.
The function is currently implemented with the help of the fypp preprocessor, by looping through all the desired types and kinds:
#:for k1, t1 in KINDS_TYPES
pure elemental function optval_${t1[0]}$${k1}$(x, default) result(y)
${t1}$, intent(in), optional :: x
${t1}$, intent(in) :: default
${t1}$ :: y
if (present(x)) then
y = x
else
y = default
end if
end function optval_${t1[0]}$${k1}$
#:endfor
Without generics, a Fortran programmer could also resort to using a preprocessor directly, such as with the following fypp macro:
#:def optval(lhs,opt,default)
if (present(${opt}$)) then
${lhs}$ = ${opt}$
else
${lhs}$ = ${default}$
end if
#:enddef
This macro however cannot be used in expressions. With Fortran 202X the new ternary if operator will make this possible using the following fypp macro:
Using the Fortran 2018 enhanced C interoperability features, it is possible to interoperate optional arguments with C, where a null pointer means the argument is not present. A Fortran procedure interface could be provided behind the scenes by a procedure in C++ with an extern "C" interface. In C++ a function template is an elegant and type-sage solution for this usage case:
template<typename T>
inline T optval(const T* opt, T value) {
T r = value;
if (opt) r = *opt;
return r;
}
What would the Fortran solution with the generics look like? Would this be a good example to motivate the generics proposals?
The text was updated successfully, but these errors were encountered:
The Fortran-lang stdlib defines a function
optval
that can be used to define provide a fallback value for an optional argument.The function is currently implemented with the help of the fypp preprocessor, by looping through all the desired types and kinds:
Without generics, a Fortran programmer could also resort to using a preprocessor directly, such as with the following fypp macro:
This macro however cannot be used in expressions. With Fortran 202X the new ternary if operator will make this possible using the following fypp macro:
or its cpp/fpp equivalent:
Using the Fortran 2018 enhanced C interoperability features, it is possible to interoperate optional arguments with C, where a
null
pointer means the argument is not present. A Fortran procedure interface could be provided behind the scenes by a procedure in C++ with anextern "C"
interface. In C++ a function template is an elegant and type-sage solution for this usage case:What would the Fortran solution with the generics look like? Would this be a good example to motivate the generics proposals?
The text was updated successfully, but these errors were encountered: