【发布时间】:2017-07-16 08:00:43
【问题描述】:
我认为operator<< 的调用会生成一个双参数函数调用。那么,为什么这不能编译呢?
#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 和我都同意这是无稽之谈。我也尽可能自动地尝试了 lambda:
auto w2 = [](auto&os, auto f) {
return os << setw(2) << setfill( '0' ) << f; };
也没有运气。
有什么提示吗?
【问题讨论】:
-
您只是将一个参数传递给需要两个参数的 lambda。此外,您将 lambda 的返回值传递给
operator<<,这是一个std::ostream&。
标签: c++ lambda operator-overloading outputstream ostream