Modern C++:Efficient and Scalable Application Development
上QQ阅读APP看书,第一时间看更新

Using default parameters

There are situations when you have one or more parameters that have values that are so frequently used that you want them to be treated as a default value for the parameter, while still having the option of allowing the caller to provide a different value if necessary. To do this, you provide the default value in the parameter list of the definition:

    void log_message(const string& msg, bool clear_screen = false) 
{
if (clear_screen) clear_the_screen();
cout << msg << endl;
}

In most cases, this function is expected to be used to print a single message, but occasionally the user may want to have the screen cleared first (say, for the first message, or after a pre-determined count of lines). To accommodate this use of the function, the clear_screen parameter is given a default value of false, but the caller still has the option of passing a value:

    log_message("first message", true); 
log_message("second message");
bool user_decision = ask_user();
log_message("third message", user_decision);

Note that the default values occur in the function definition, not in a function prototype, so if the log_message function is declared in a header file the prototype should be:

    extern void log_message(const string& msg, bool clear_screen);

The parameters that can have default values are the right-most parameters.

You can treat each parameter with a default value as representing a separate overload of the function, so conceptually the log_message function should be treated as two functions:

    extern void log_message(const string& msg, bool clear_screen); 
extern void log_message(const string& msg); // conceptually

If you define a log_message function that has just a const string& parameter, then the compiler will not know whether to call that function or the version where clear_screen is given a default value of false.