更多 C++ 慣用法/命名引數
外觀
模擬在其他語言中找到的命名(鍵值對)引數傳遞風格,而不是基於位置的引數。
方法鏈,流暢介面
當函式接受多個引數時,程式設計師必須記住型別和傳遞引數的順序。此外,預設值只能賦予最後一個引數,因此無法指定後一個引數並對先前引數使用預設值。命名引數允許程式設計師以任何順序將引數傳遞給函式,並且這些引數由名稱區分。因此,程式設計師可以顯式地傳遞所有必要的引數和預設值,而無需擔心函式宣告中使用的順序。
命名引數慣用法使用代理物件來傳遞引數。函式的引數被捕獲為代理類的成員資料。該類為每個引數公開設定方法。設定方法按引用返回 *this* 物件,以便其他設定方法可以連結在一起以設定剩餘的引數。
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;
}
- 命名引數慣用法,Marshal Cline