希望谁读取该知道默认参数:参数列表中任意点的默认参数是否可能?
void setCase (string &str, int form = UPPERCASE)
{
for (char &c : str)
c = (form == UPPERCASE ? c & ~0x20 : c | 0x20); //this bit differentiates english uppercase and lowercase letters
}
int main()
{
string s1 = "HeLlO", s2 = s1, s3 = s1;
setCase (s1, UPPERCASE); //now "HELLO"
setCase (s2, LOWERCASE); //now "hello"
setCase (s3); //now "HELLO" due to default argument
}
使用默认参数的一个缺点是,你必须在列表的末尾开始拖欠参数。有时候这需要将参数重新排列成一个看起来很笨的命令。为了解决这个问题,必须分开重载。
让我带一个窗口API函数,FindWindow,即通过类的姓名,职务,或两者是找到一个窗口,作为一个例子:
HWND WINAPI FindWindow(//returns handle to window
__in_opt LPCTSTR lpClassName, //param equivalent to const TCHAR *, classes are like templates for windows
__in_opt LPCTSTR lpWindowName //the text that appears on the title bar (for normal windows, for things like buttons, it's what text is on the button)
);
为了总结这一点,可能要默认搜索选项成为冠军。有三种理想的实现方式(假设已经使用了其他包装技术)。完美的解决方案很可能如下:
Window FindWindow (LPCTSTR className = 0, LPCTSTR windowName){...}
第二种解决方案是重载函数的一个版本只接受标题,另一个同时接受。第三个是切换参数的顺序。
第二个问题的主要问题是,对于较长的列表,随着列表增长,重载的空间量可能会变得非常大。第三个问题的主要问题是,任何一个预先使用这个函数的人都会被用来首先指定类名。这也适用于常规的C++函数。参数往往具有自然顺序。
第一种解决方案的主要问题当然是它不受C++语言支持。我的问题是:
未来有没有这种可能性?
例如,编译器能否在需要时自动生成适当的重载?
不喜欢吗?使用不同的语言,如Python,它使用[keyword arguments](http://docs.python.org/release/1.5.1p1/tut/keywordArgs.html)。 ['subprocess.Popen'](http://docs.python.org/library/subprocess.html#subprocess.Popen)就是一个很好的例子。 – 2012-04-05 03:06:33
我可以和它一起生活。我只是有兴趣知道(可能很多其他人也是如此),如果随着更新的C++新增功能进入语言,这可能会发生变化。我记得另一种语言(可能是Python)适合传递参数,因为能够判断参数是否默认或用户是否传递了默认值。 – chris 2012-04-05 03:10:35
也许阅读[为什么可选参数必须出现在声明的末尾](http://stackoverflow.com/questions/2896106/why-optional-parameters-must-appear-at-the-end-of-the-declaration ) 可能有帮助。 – 2012-04-05 03:11:48