Last modified on 21 June 2011, at 11:17

More C++ Idioms/Named Parameter

Named ParameterEdit

IntentEdit

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

Also Known AsEdit

MotivationEdit

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 CodeEdit

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.

class X
{
  public:
    int a;
    char b;
 
    X() : a(-999), b('C') {}  // Initialize with default values, if any.
    X & setA(int i) { a = i; return *this; } // non-const function
    X & setB(char c) { b = c; return *this; } // non-const function
 
    static X create() {
      return X();
    }
};
 
std::ostream & operator << (std::ostream & o, X const & x)
{
	o << x.a << " " << x.b;
	return o;
}
 
int main (void)
{
  // The following code uses the named parameter idiom.
  std::cout << X::create().setA(10).setB('Z') << std::endl;
}

Known UsesEdit

Related IdiomsEdit

ReferencesEdit