2012-06-01 93 views
2

C++標準如何定義一般的操縱器或操縱器的識別?C++操縱器?

例如:

using namespace std; 
ostream& hello_manip(ostream& os){ 
    os<<"Hello there, fine fellow!"; return os; 
} 
int main(){ 
    cout<<hello_manip; 
} 

代碼COUT < < hello_manip似乎被翻譯成操作者< <(COUT,hello_manip)cout.operator < <(hello_manip),但取而代之的是形式hello_manip(cout)

回答

8

存在operator<<的超載,它接受函數指針並調用它。沒有魔法介入。

標準的27.7.3.6.3節描述了簡單操縱器(如你的)的處理。

basic_ostream<charT,traits>& operator<<(basic_ostream<charT,traits>& (*pf) basic_ostream<charT,traits>&))

  1. 影響:無。不表現爲格式化的輸出功能(如27.7.3.6.1中所述)。
  2. 返回:pf(*this)

basic_ostream<charT,traits>& operator<<(basic_ios<charT,traits>& (*pf) basic_ios<charT,traits>&))

  1. 效果:調用pf(*this)。該插入器不具有格式化輸出功能(如27.7.3.6.1中所述)。
  2. 退貨:*this

basic_ostream<charT,traits>& operator<<(ios_base& (*pf)(ios_base&))

  1. 效果:調用pf(*this)。該插入器不具有格式化輸出功能(如27.7.3.6.1中所述)。
  2. 退貨:*this

更復雜的機械手(其中接受參數和執行狀態)被返回仿函數對象,它有自己的operator<<重載實現。

+0

哦,哇,我怎麼錯過了。現在這是完全意義上的。我甚至不知道我是否應該在這裏留下這個問題 - 這可能看起來有誤導性。 – Eximius

+0

@Eximius,你應該保持它,以防其他人出現並找到它。他們可能會有和你一樣的尤里卡。 – chris