gpt4 book ai didi

c++ - 如何编写带有参数的函数,其中类型是用 'auto' 字推导的?

转载 作者:太空狗 更新时间:2023-10-29 19:37:20 25 4
gpt4 key购买 nike

我正在寻找一种干净的 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),是否可以编写更优雅的函数,因为不允许自动输入参数?谢谢!

最佳答案

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

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

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

关于c++ - 如何编写带有参数的函数,其中类型是用 'auto' 字推导的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54134573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com