![](/img/trans.png)
[英]How to provoke a compile-time error if a specific overload of a function is called?
[英]how to count number of a specific function be called at compile time
一個程序被分成N個函數。
像下面的代碼片段:調用每個函數后,我想顯示進度count/N
如何在編譯時計算 N?
#include <iostream>
using namespace std;
double progress()
{
int const total = 4; // how to get 4?
static int counter = 0;
return static_cast<double>(counter++) / static_cast<double>(total);
}
int main()
{
cout << progress() << endl; // 0.25
cout << progress() << endl; // 0.5
cout << progress() << endl; // 0.75
cout << progress() << endl; // 1.0
return 0;
}
我嘗試了 constexpr 函數,但不能增加變量。
想象一下下面的代碼:
int main() {
cout << "N = ";
int N;
cin >> N;
for (int i = 0; i < N; ++i) cout << 'progress()' << endl;
}
絕對沒有辦法,編譯器可以知道函數會執行多少次。 因此,您需要使用數據的邏輯來確定數字。
如果您想知道在沒有循環、遞歸、條件等的情況下調用progress
的次數,我能想到的唯一方法是在源文件上使用外部工具。 例如
cat source.cpp | grep -o progress() | wc -l
只需記住從結果中減去 1,這就是函數定義的原因。
你不能這樣做,但你可以通過在N
(函數調用計數)已知后進行打印來偽造它。
static struct counter_impl {
int n = 0;
constexpr void operator ()() noexcept { ++n; }
friend std::ostream& operator<<(std::ostream& os, counter_impl const& self) {
os << std::fixed;
std::generate_n(std::ostream_iterator<double>(os, "\n"), self.n,
[i = 1, N = static_cast<double>(self.n)] () mutable { return i++ / N; });
return os << std::defaultfloat;
}
} counter;
int main() {
counter();
std::cout << counter; // 1.00
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.