撰寫您自己的 Manipulators,不需引數

撰寫不使用引數的 manipulators 需要不致於類別的衍生或使用複雜的巨集。假設您的印表機需要對 <ESC> [參加粗體的模式。您可以直接在資料流中插入此組:

cout << "regular " << '\033' << '[' << "boldface" << endl;

或者您可以定義bold manipulator,插入的字元:

ostream& bold( ostream& os ) {
    return os << '\033' << '[';
}
cout << "regular " << bold << "boldface" << endl;

全域定義bold函式會ostream參考引數,並傳回ostream的參考。它不是成員函式或一位朋友因為不需要存取任何私用類別的項目。bold函式會連接至資料流,因為資料流的<<運算子為多載接受 [函式,該型別使用外觀類似這樣的宣告:

_Myt& operator<<(ios_base& (__cdecl *_Pfn)(ios_base&))
{   
   // call ios_base manipulator
   (*_Pfn)(*(ios_base *)this);
   return (*this);
}

您可以使用這項功能來擴充其他多載的運算子。如此一來,它是附隨性的bold插入的資料流中的字元。當它會插入至資料流,不一定是相鄰的字元進行列印時,會呼叫函式。因此,列印就有可能延遲因緩衝資料流。

請參閱

參考

輸出資料流