问题
I'm new to C++ templates and I'm trying to write a function which returns a chrono::duration with the specified time unit and type. For instance, this line gives me the time difference in seconds as double:
std::chrono::duration<double> secd =
std::chrono::duration_cast<std::chrono::duration<double,std::ratio<1>>>(end - start);
I have a class function which gives me a time duration, and I would like to use templates to indicate the type and unit for the return value (in the previous example, that would be double and ratio<1>). What I would like to have is something similar to this pseudocode:
template typename<class T, class R> std::chrono::duration<T, R> getStepTime() {
return std::chrono::duration_cast<std::chrono::duration<T, R>>(_time);
}
where _time
is a class member with the duration. All my attempts so far didn't even compile.
In case there is a better way to achieve this without using templates, I'm all ears.
回答1:
Bad usage of typename
and there's a missing closing >
in your template. Here is a tweaked example to test compilation :
template <typename T, typename R>
std::chrono::duration<T, R> getStepTime()
{
std::chrono::duration<T, R> duration;
return std::chrono::duration_cast<std::chrono::duration<T, R>>(duration);
}
http://ideone.com/QGYm8u
回答2:
Bad usage of typename
keyword; try
template<typename T, typename R>
std::chrono::duration<T, R> getStepTime(Step step) {
return
std::chrono::duration_cast<std::chrono::duration<T, R>>(_time);
}
but you should show more code. Your example is too small to be even tested.
来源:https://stackoverflow.com/questions/20813366/function-to-return-a-chronoduration-using-templates-for-the-time-unit