Home
ObjexxFCL 4.2
 

Optional

Optional is a class template providing the semantics of Fortran's OPTIONAL arguments. Optional, like Fortran's OPTIONAL, behaves differently from C++ arguments with default values in a few ways:

  • Optional arguments can be omitted and can be tested for presence.
  • Optional arguments can be intermixed with regular arguments.
  • Since C++ doesn't have keyword arguments a placeholder Omit argument can be used when arguments follow.

Optional arguments are declared as pass-by-value proxies taking an Omit default value:

Optional< Type > arg = _

Notes on Optional usage:

  • The Type can be const-qualified.
  • Optional arguments are declared to accept a default Omit value so that they can be omitted. An Omit object named _ (underscore character) is provided.
  • Optional arguments can be omitted from a call if no following arguments are needed.
  • To omit Optional arguments followed by other arguments an Omit object can be passed. The supplied underscore object, _, can be used for consise usage, such as fxn( a, b, _, d ).
  • Optional arguments can automatically convert to the contained object.
  • Explicit conversion to the contained object is available with the syntax optional().
  • For dot and function call usage the explicit syntax is needed, such as optional().method() or optional()( arg ).
  • Typedefs for common types are provided, such as Optional_int for Optional< int >.
  • While Optional is very useful for code converted from Fortran, native C++ arguments with default values should be preferred where sufficient for new code.

Required

Required is the complementary analog of Optional for use when you have Optional arguments followed by non-optional arguments and you don't want to reorder the arguments to put the Optional arguments all at the end. Required arguments can follow Optional arguments and because they accept default arguments the Optional arguments can preceed them. The Required arguments are declared like Optional with a default Omit argument but at run time omitting them is an error.

Required is primarily useful for code converted from Fortran where OPTIONAL arguments are not all at the end of a function's argument list and reordering the list is not desired. In new code it is suggested to put Optional arguments at the end of the argument list. It is also best to use C++ default arguments instead of Optional when their semantics suffice: Optional proxy creation has some overhead that could impact performance in high call count functions.