Function to return a chrono::duration using templates for the time unit

穿精又带淫゛_ 提交于 2019-12-13 03:38:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!