使用时间单位模板返回 chrono::duration 的函数 [英] Function to return a chrono::duration using templates for the time unit

查看:42
本文介绍了使用时间单位模板返回 chrono::duration 的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C++ 模板的新手,我正在尝试编写一个函数,该函数返回具有指定时间单位和类型的 chrono::duration.例如,这一行给了我两倍的时间差(以秒为单位):

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);

我有一个类函数,它给了我一个持续时间,我想使用模板来指示返回值的类型和单位(在前面的例子中,这将是 double 和比率<1>).我想要的是类似于这个伪代码的东西:

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);
}

其中 _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.

推荐答案

typename 的错误使用,并且模板中缺少结束 >.这是一个测试编译的调整示例:

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

这篇关于使用时间单位模板返回 chrono::duration 的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆