More C++ Idioms/Named Parameter

= Named Parameter =

Intent
Simulate named (key-value pair) parameter passing style found in other languages instead of position-based parameters.

Also Known As
Method chaining, Fluent interface

Motivation
When a function takes many parameters, the programmer has to remember the types and the order in which to pass them. Also, default values can only be given to the last parameters, so it is not possible to specify one of the later parameters and use the default value for former ones. Named parameters let the programmer pass the parameters to a function in any order and they are distinguished by a name. So the programmer can explicitly pass all the needed parameters and default values without worrying about the order used in the function declaration.

Solution and Sample Code
Named parameter idiom uses a proxy object for passing the parameters. The parameters of the function are captured as data members of the proxy class. The class exposes set methods for each parameter. The set methods return the *this object by reference so that other set methods can be chained together to set remaining parameters.

Known Uses

 * bgl_named_params template in the Boost Graph Library (BGL)
 * boost::parameter

Related Idioms

 * Named Template Parameters