c++ - 子类化std::chrono::duration

标签 c++ chrono

我有一段代码,其中std::chrono::duration<int64_t, std::milli>是子类化的,并用于创建std::chrono::time_point,如下所示:

#include <chrono>

class my_duration : public std::chrono::duration<int64_t, std::milli>
{ /* snip */ };

int main() 
{
    typedef std::chrono::time_point< std::chrono::system_clock, my_duration > my_time_point;
    my_time_point t( my_duration{} );
    //....
}

在使用GCC <10时,这似乎可以编译并且可以正常工作。但是,在使用GCC 10时,std::chrono::time_point中的静态断言将失败,并且:

/opt/wandbox/gcc-head/include/c++/11.0.0/chrono:764:37: error: static assertion failed: duration must be a specialization of std::chrono::duration



在以下链接中可以看到,该链接还演示了clang给出了相同的错误:https://wandbox.org/permlink/CQw6fWt4kZ1xYdet

在std::chrono中,失败的断言是由于__is_duration使用的time_point结构:

template<typename _Tp>
  struct __is_duration
  : std::false_type
  { };

template<typename _Rep, typename _Period>
  struct __is_duration<duration<_Rep, _Period>>
  : std::true_type
  { };

//... further down, in time_point: 
static_assert(__is_duration<_Dur>::value,
    "duration must be a specialization of std::chrono::duration");

我对此的理解是__is_duration<my_duration>将是导致静态断言失败的std::false_type

所以,我的问题是:这是否意味着无法继承std::chrono::duration并将派生类与time_point一起使用?还是有一些技巧可以使duration子类传递静态断言?

最佳答案

std::time_point始终要求持续时间类型为std::duration的特殊化。如果不是,则程序格式不正确(又称:编译错误)。这可能只是GCC首次执行该要求。

duration派生实际上并没有任何有用的目的。

关于c++ - 子类化std::chrono::duration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62045915/

相关文章:

c++ - 持久化 std::chrono time_point 实例

c++ - 如何创建用于 std::chrono 函数的自定义时钟?

c++ - 如何使用模板在 C++ 中使用 `using` 创建别名(创建参数化别名)?

c++ - C++中 "using namespace std;"的作用是什么?

c++ - 如何使用构造函数初始值设定项列表中的 n 个元素初始化 std::vector<std::time_t>

c++ - 为什么 chrono 有自己的命名空间?

C++ std::chrono::high_resolution_clock time_since_epoch 返回的数字太小。如何获得自 1970 年以来以微秒为单位的正确时间?

C++11:将 time_point 增加一秒

c++ - 为什么我的 C++ 模板函数不会产生 `undeclared identified` 编译错误?

c++ - 改变音量 win32 c++