简体   繁体   English

子类化 std::chrono::duration

[英]Subclassing std::chrono::duration

I have a piece of code where std::chrono::duration<int64_t, std::milli> is subclassed, and used to create a std::chrono::time_point , like so:我有一段代码,其中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{} );
    //....
}

This was seemingly compiling and working fine when using GCC < 10. However, when using GCC 10, a static assertion in std::chrono::time_point will fail with:当使用 GCC < 10 时,这似乎编译和工作正常。但是,当使用 GCC 10 时,staticchrono 断言将失败:

/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 /opt/wandbox/gcc-head/include/c++/11.0.0/chrono:764:37:错误:static 断言失败:duration 必须是 std::chrono::duration 的特化

This can be seen at the following link, which also demonstrates that clang gives the same error: https://wandbox.org/permlink/CQw6fWt4kZ1xYdet这可以在以下链接中看到,这也表明 clang 给出了相同的错误: https://wandbox.org/permlink/CQw6fWt4kZ1xYdet

In std::chrono, the failing assert is due to the __is_duration structs used by time_point :在 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");

My understanding of it is that __is_duration<my_duration> will be an std::false_type causing the static assert to fail.我的理解是__is_duration<my_duration>将是一个std::false_type导致 static 断言失败。

So, my question is: does this mean it isn't possible to subclass std::chrono::duration and use the derived class with time_point?所以,我的问题是:这是否意味着不可能继承 std::chrono::duration 并将派生的 class 与 time_point 一起使用? Or is there some trick that will allow the duration subclass to pass the static assertion?或者是否有一些技巧可以让持续时间子类通过 static 断言?

std::time_point has always required that the duration type be a specialization of std::duration . std::time_point始终要求持续时间类型是std::duration的特化。 If it isn't, then the program is ill-formed (aka: compile error).如果不是,则程序格式错误(又名:编译错误)。 This may just be the first time GCC implemented that requirement.这可能只是 GCC 第一次实现该要求。

Deriving from duration doesn't really serve any useful purpose.duration派生并没有真正起到任何有用的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM