我認爲operator<<
的調用會產生一個雙參數函數調用。那麼,爲什麼不編譯呢?如何爲ostream創建一個lambda?
#include <iostream> // ostream
#include <iomanip> // setw, setfill
using std::ostream; using std::setw; using std::setfill;
struct Clock {
int h_, m_, s_;
Clock(int hours, int minutes, int seconds)
: h_{hours}, m_{minutes}, s_{seconds} {}
void setClock(int hours, int minutes, int seconds) {
h_ = hours; m_ = minutes; s_ = seconds;
}
friend ostream& operator<<(ostream&os, const Clock& c) {
auto w2 = [](ostream&os, int f) -> ostream& {
return os << setw(2) << setfill('0') << f; };
return os << w2(c.h_) <<':'<<w2(c.m_)<<':'<<w2(c.s_); // ERROR
}
};
錯誤的是(GCC-6)
$ g++-6 -std=gnu++1y ...
file.cpp: In function ‘std::ostream& operator<<(std::ostream&, const Clock&)’:
file.cpp:745:33: error: no match for call to ‘(operator<<(std::ostream&, const Clock&)::<lambda(std::ostream&, int)>) (const int&)’
return os << w2(c.h_) <<':'<<w2(c.m_)<<':'<<w2(c.s_);
^
我也試過電話os << w2(os,c.h_)
但gcc和我都認爲是無稽之談。此外,我嘗試儘可能自動拉姆達:
auto w2 = [](auto&os, auto f) {
return os << setw(2) << setfill('0') << f; };
也沒有運氣。
任何提示?
您只將一個參數傳遞給需要兩個參數的lambda表達式。你也將你的lambda的返回值傳遞給'operator <<'這是一個'std :: ostream&'。 – Galik