我正在编写一个包含许多长for循环的程序,我想为每个循环添加一个进度条指示器。为此,我写了
struct ProgressBar
来完成此任务。界面如下:
struct ProgressBar {
int start, end; // starting and ending values of the loop variable
const int &curr; // const reference to the loop variable
/* Update the progress bar by inspecting the current value of "curr" */
void update();
/* Constructor; the reference "curr" is initialized in the member initializer list, as it must be */
ProgressBar(int start, int end, const int &curr);
~ProgressBar() {
cout << "100% done" << endl;
}
};
理想化的用法是
for (auto [i, pb] = pair{0, ProgressBar(0, 100, i)}; i <= 100; ++i) {
pb.update();
/* ... */
}
这不起作用至少有两个原因:
ProgressBar(0, 100, i)
会导致编译器错误,因为它依赖于循环变量 i
,而其类型尚未推导 (error: use of ‘i’ before deduction of ‘auto’
)。ProgressBar(0, 100, i)
需要在 i
之后求值,但我相信 pair
构造函数,像所有 C++ 函数一样,不保证函数参数求值的任何特定顺序。我应该做什么的任何设计想法?
为什么需要两个变量来计算循环?
修改进度条,以便它知道何时到达终点。
#include <iostream>
class PB
{
int beg;
int end;
int current;
public:
PB(int beg, int end)
: beg(beg)
, end(end)
, current(beg)
{}
operator bool() {return current != end;}
PB& operator++() {++current;return *this;}
void update()
{
std::cout << current << "\n";
}
};
int main()
{
for (auto pb = PB(1,100); pb; ++pb) {
pb.update();
}
}