【问题标题】:std::chrono supertype, function argument passingstd::chrono 超类型,函数参数传递
【发布时间】:2012-11-19 11:34:14
【问题描述】:

我有

auto now = std::chrono::high_resolution_clock::now();

我想将它传递给一个使用通用类型的时间点的函数。我不想指定所用时钟的分辨率或类型。

我尝试过使用

void my_function(std::chrono::time_point time_point);

但没有成功。因为显然 std::chrono::time_point 不是类型。

【问题讨论】:

  • 我的意思是,您计划使用time_point 界面的哪一部分,不依赖于所用时钟的分辨率或类型?

标签: c++ c++11 chrono


【解决方案1】:

std::chrono::time_point 是一个模板类,它至少需要一个clock 模板参数。

要么明确设置时钟,比如

void my_function(std::chrono::time_point<std::chrono::high_resolution_clock> time_point);

或者你可以让你的函数本身成为一个模板:

template<typename Clock>
void my_function(std::chrono::time_point<Clock> time_point);

在最后一种情况下,您实际上不必在调用函数时指定模板参数,编译器会为您计算出来:

my_function(now);

【讨论】:

  • 是的,使函数成为模板似乎是这里唯一的选择。顺便说一句,用不同的时钟减去两个不同的 time_points 就可以正常工作(而加上 time_points 则不行,这将如何定义!?)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-04
  • 1970-01-01
相关资源
最近更新 更多