我认为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