How to write function with parameter which type is deduced with 'auto' word?

  • A+
Category:Languages

I am searching a clean c++11 (up to c++17) way to write a function that simply writes fps to the output stream with given 'start' and 'stop' times (e.g. given an interval times). So I have this code, for example:

#include <iostream> int main(int argc, char** argv) {     typedef std::chrono::high_resolution_clock time_t;     while (1) {         auto start = time_t::now();          // here is the call of function that do something         // in this example will be printing         std::cout << "Hello world!"          auto stop = time_t::now();         fsec_t duration = stop - start;          double seconds = duration.count();         double fps = (1.0 / seconds);          std::stringstream s;         s << "FPS: " << fps;          std::cout << s.str();     } } 

And I want to do something like:

#include <iostream>  std::ostream & printFPS(std::ostream &stream, auto start);  int main(int argc, char** argv) {      while (1) {         auto start = std::chrono::high_resolution_clock::now();          // here is the call of function that do something         // in this example will be printing         std::cout << "Hello world!"          printFPS(std::cout, start);     } }  std::ostream & printFPS(std::ostream &stream, auto start){      auto stop = std::chrono::high_resolution_clock::now();     std::chrono::duration<float> duration = stop - start;      double seconds = duration.count();     double fps = (1.0 / seconds);      std::stringstream s;     s << "FPS: " << fps;      return stream << s.str(); } 

GCC gives me tips that deduced type of 'start' is std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1, 1000000000> > >, but I don't want to write in function this type (may be deduction will change(?), also it is very long and needed typedef), is it possible to write more elegant function, since auto in parameters is not allowed? Thank you!

 


You can use decltype to deduce the time type and use it as the type of the argument.

using time_type = decltype(std::chrono::high_resolution_clock::now());  std::ostream & printFPS(std::ostream &stream, time_type start); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: