问题
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!
回答1:
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);
回答2:
The expression std::chrono::high_resolution_clock::now()
returns a value of type std::chrono::high_resolution_clock::time_point
. So you can do that directly:
std::ostream& printFPS(std::ostream&, std::chrono::high_resolution_clock::time_point );
But your print function probably doesn't care about which Clock you got your time_point
from. It just cares that it got a time_point
, so you can do this more generally:
template <typename Clock, typename Duration>
std::ostream& printFPS(std::ostream&, std::chrono::time_point<Clock, Duration> );
回答3:
This is a simple case of template declaration (although C++20 may be easier and accept your syntax):
template<typename Duration>
std::ostream & printFPS(std::ostream &stream, Duration start);
And then definition:
template<typename Duration>
std::ostream & printFPS(std::ostream &stream, Duration start)
{}
来源:https://stackoverflow.com/questions/54134573/how-to-write-function-with-parameter-which-type-is-deduced-with-auto-word