如何用“自动”字推导带有参数类型的函数?

时间:2019-01-10 18:08:18

标签: c++ c++11 c++14 c++17

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

#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),是否可以编写更精美的函数,因为不允许使用自动输入参数?谢谢!

3 个答案:

答案 0 :(得分:9)

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

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

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

答案 1 :(得分:7)

表达式std::chrono::high_resolution_clock::now()返回类型为std::chrono::high_resolution_clock::time_point的值。因此,您可以直接执行以下操作:

std::ostream& printFPS(std::ostream&, std::chrono::high_resolution_clock::time_point );

但是您的打印功能可能并不关心您从time_point获得时钟的时间。它只是在乎它有一个time_point,因此您可以更一般地执行此操作:

template <typename Clock, typename Duration>
std::ostream& printFPS(std::ostream&, std::chrono::time_point<Clock, Duration> );

答案 2 :(得分:3)

这是模板声明的简单情况(尽管C ++ 20可能更容易接受语法):

template<typename Duration>
std::ostream & printFPS(std::ostream &stream, Duration start);

然后定义:

template<typename Duration>
std::ostream & printFPS(std::ostream &stream, Duration start)
{}