More C++ Idioms/Named Parameter
From Wikibooks, the open-content textbooks collection
Contents |
[edit] Intent
When a function or a class template takes many parameters, the programmer has to remember 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 or a class template 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.
[edit] Also Known As
[edit] Motivation
[edit] Solution and Sample Code
class X { public: int a; char b; X() : a(0), b(0) {} X & setA(int i) { a = i; return *this; } // non-const function X & setB(char c) { b = c; return *this; } // non-const function }; std::ostream & operator << (std::ostream & o, X const & x) { o << x.a << " " << x.b; return o; } X createX() // returns X by value. { return X(); } int main (void) { // The following code uses the named parameter idiom. std::cout << createX().setA(10).setB('Z') << std::endl; }