简体   繁体   中英

how to count number of a specific function be called at compile time

A program is divided into N functions.

Like the following code snippets: after calling each function, I wanna show the progress count/N

how to count N at compile time ?

#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;
}

I tried constexpr function, but cannot increment a variable.

Imagine the following code:

int main() {
    cout << "N = ";
    int N;
    cin >> N;
    for (int i = 0; i < N; ++i) cout << 'progress()' << endl;
}

There is absolutely no way, the compiler can know how many times the function will be executed. So you need to determine the number using the logic of your data.

If you want to know how many times you call progress without loops, recursions, conditions etc., the only way I can think of is using external tool on the source file. Eg

cat source.cpp | grep -o progress() | wc -l

Just remember to subtract 1 from the result, which accounts for the function definition.

You can't do it, but you could fake it by making the printing happen after N (function call count) is known.

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
}

Live example on compiler explorer

Unfortunately, you cannot.

This is not something that can be determined at compile time.

See https://en.wikipedia.org/wiki/Halting_problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM