亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何指定指向重載函數的指針?

如何指定指向重載函數的指針?

C++
白板的微信 2019-08-03 07:03:55
如何指定指向重載函數的指針?我想將重載的函數傳遞給std::for_each()算法。例如,class A {     void f(char c);     void f(int i);     void scan(const std::string& s) {         std::for_each(s.begin(), s.end(), f);     }};我希望編譯器能夠解析f()迭代器類型。顯然,它(GCC 4.1.2)沒有做到這一點。那么,我如何指定f()我想要?
查看完整描述

3 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

你可以用static_cast<>()指定哪個f根據函數指針類型所隱含的函數簽名使用:


// Uses the void f(char c); overload

std::for_each(s.begin(), s.end(), static_cast<void (*)(char)>(&f));

// Uses the void f(int i); overload

std::for_each(s.begin(), s.end(), static_cast<void (*)(int)>(&f)); 

或者,你也可以這樣做:


// The compiler will figure out which f to use according to

// the function pointer declaration.

void (*fpc)(char) = &f;

std::for_each(s.begin(), s.end(), fpc); // Uses the void f(char c); overload

void (*fpi)(int) = &f;

std::for_each(s.begin(), s.end(), fpi); // Uses the void f(int i); overload

如果f是一個成員函數,那么您需要使用mem_fun,或者對于您的情況,使用Dobb博士的文章中給出的解決方案.




查看完整回答
反對 回復 2019-08-04
  • 3 回答
  • 0 關注
  • 454 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號