使用时间单位模板返回 chrono::duration 的函数

编程入门 行业动态 更新时间:2024-10-26 10:32:54
本文介绍了使用时间单位模板返回 chrono::duration 的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我是 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/QGYm8u

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

更多推荐

[db:关键词]

本文发布于:2023-04-30 12:17:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393526.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   模板   单位   时间   chrono

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!