加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何使用’auto’字推导出类型参数的函数?

发布时间:2020-12-16 10:44:45 所属栏目:百科 来源:网络整理
导读:我正在搜索一个干净的c 11(直到c 17)方式来编写一个函数,该函数只需将fps写入输出流,并给定’start’和’stop’次(例如给定间隔时间). 所以我有这个代码,例如: #include iostreamint main(int argc,char** argv) { typedef std::chrono::high_resolution_cl
我正在搜索一个干净的c 11(直到c 17)方式来编写一个函数,该函数只需将fps写入输出流,并给定’start’和’stop’次(例如给定间隔时间).
所以我有这个代码,例如:

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

我想做的事情如下:

#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给出了一些提示,推断出’start’的类型是std :: chrono :: time_point< std :: chrono :: _ V2 :: system_clock,std :: chrono :: duration< long int,std :: ratio< 1,1000000000&gt ; > >,但是我不想在函数中写这种类型(可能是演绎会改变(?),也很长而且需要typedef),是否可以编写更优雅的函数,因为auto in参数不是允许?谢谢!

解决方法

您可以使用decltype推导时间类型并将其用作参数的类型.

using time_type = decltype(std::chrono::high_resolution_clock::now());

std::ostream & printFPS(std::ostream &stream,time_type start);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读