Sam P
Sam P

Reputation: 1841

C++ Generic Function Parameter (different arguments)

I'm trying to write a benchmark function, but I need to be able to pass in any function to be tested. The functions that are being passed in are all of return type void, but their arguments vary. I'm sure this is a simple thing to do, but I'm not sure of the best way to approach it.

// 95% confidence interval
void benchmark(int n)
{
  int res[n];
  for (int i = 0; i < n; i++) {
    uint64_t start = GetTimeMs64();
    // **TODO: code to benchmark...**
    uint64_t end = GetTimeMs64();
    res[i] = end - start;
  }

  double avg = 0.0;
  for (int i = 0; i < n; i++) avg += res[i];
  avg /= double(n);

  double variance = 0.0;
  for (int i = 0; i < n; i++) {
    variance += ((res[i] - avg) * (res[i] - avg));
  }
  variance /= double(n - 1);
  cout << "Sample mean: " << avg << " +/- " << (1.96 * (sqrt(variance) / sqrt(n))) << endl;
}

For instance, I want to do something like:

void A(int a, int b) { return a + b; }
void B(int a) { return a * a; }
benchmark(100, A);
benchmark(100, B);

Upvotes: 0

Views: 146

Answers (1)

user657267
user657267

Reputation: 21000

You can make your benchmark function a template with something like the following

#include <utility>
void A(int, char) { }
void B(int) { }

template<typename... Args>
void benchmark(int n, void(&func)(Args...), Args&&... args)
{
  func(std::forward<Args>(args)...);
}

int main()
{
  benchmark(1, A, 2, 'c');
  benchmark(1, B, 2);
}

If necessary you can make it even more generic by adding an extra template parameter for the return type.

Upvotes: 2

Related Questions