user2723342
user2723342

Reputation: 93

Structured binding argument deduction fails

I am trying to expand this answer to return the result of the function in addition to the CPU time. Here is my code:

#include <chrono>
#include <iostream>
#include <utility>

template <typename F, typename... Args>
auto MeasureFunctionCpuTime(F func, Args&&... args) {
  using TimeVar = std::chrono::high_resolution_clock::time_point;
  constexpr auto get_now = std::chrono::high_resolution_clock::now;
  TimeVar t1 = get_now();
  const auto result = func(std::forward<Args>(args)...);
  const double cpu_time =
      std::chrono::duration_cast<std::chrono::nanoseconds>(get_now() - t1)
          .count();
  return {result, cpu_time};
}

double AddTwoNumbers(const double a, const double b) { return a + b; }

int main() {
  auto [result, cpu_time] = MeasureFunctionCpuTime(AddTwoNumbers, 1.0, 3.0);
  std::cout << result << "\n";
  std::cout << cpu_time << "\n";
}

and I compile it using the following command line:

g++ main.cpp -o main -std=c++17 -lstdc++ -o2

But I receive the following error:

main.cpp: In instantiation of ‘auto MeasureFunctionCpuTime(F, Args&& ...) [with F = double (*)(double, double); Args = {double, double}]’:
main.cpp:20:75:   required from here
main.cpp:14:27: error: returning initializer list
   return {result, cpu_time};
                           ^
main.cpp: In function ‘int main()’:
main.cpp:20:8: error: ‘void <structured bindings>’ has incomplete type
   auto [result, cpu_time] = MeasureFunctionCpuTime(AddTwoNumbers, 1.0, 3.0);
        ^~~~~~~~~~~~~~~~~~

Why this initializer list fails?

Update: Following Bob's hint, I managed to return a pair by changing the return value of the function to this line:

  return std::pair<decltype(result), double>{result, cpu_time};

Is there any downside to this approach?

Upvotes: 0

Views: 232

Answers (0)

Related Questions