本文介绍了如何用“自动”字推导带有参数类型的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在寻找一种干净的c ++ 11(最高为c ++ 17)的方式来编写一个函数,该函数可以在给定的开始和停止时间(例如给定的间隔时间)内将fps写入输出流。
因此,我有以下代码,例如:

I am searching a clean c++11 (up to c++17) way to write a function that simply writes fps to the output stream with given 'start' and 'stop' times (e.g. given an interval times).So I have this code, for example:

#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给了我一些提示,即推断出的开始类型为 std :: chrono :: time_point< std :: chrono :: _ V2 :: system_clock,std :: chrono :: duration< long int,std :: ratio< 1,1000000000> > > ,但是我不想在这种类型的函数中编写(可能是演绎会改变(?),而且它很长,需要typedef),是否有可能编写出更精美的函数,因为不允许使用自动输入参数?谢谢!

GCC gives me tips that deduced type of 'start' is std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1, 1000000000> > >, but I don't want to write in function this type (may be deduction will change(?), also it is very long and needed typedef), is it possible to write more elegant function, since auto in parameters is not allowed? Thank you!

推荐答案

您可以使用 decltype 推断时间类型并使用它作为参数的类型。

You can use decltype to deduce the time type and use it as the type of the argument.

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

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

这篇关于如何用“自动”字推导带有参数类型的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:10