1

我有以下代码:

#include <chrono>

struct SteadyTime : std::chrono::steady_clock::time_point {
    using time_point::time_point;

    static SteadyTime now() {
      return clock::now();
    }
};

这适用于 Visual Studio 2019,但使用 gcc 8.3 我收到以下错误:

<source>: In static member function 'static SteadyTime SteadyTime::now()':

<source>:7:24: error: could not convert 'std::chrono::_V2::steady_clock::now()' from 'std::chrono::_V2::steady_clock::time_point' {aka 'std::chrono::time_point<std::chrono::_V2::steady_clock, std::chrono::duration<long int, std::ratio<1, 1000000000> > >'} to 'SteadyTime'

       return clock::now();

              ~~~~~~~~~~^~

Compiler returned: 1

这段代码似乎是标准的,那么可能有什么问题?

4

1 回答 1

2

你想要做的基本上是这样的:

struct Base
{};

Base getBase();

struct Derived : Base
{
    static Derived get() { return getBase(); }
};

https://godbolt.org/z/KZyP99

这不起作用,因为编译器不知道如何将 a 转换Base为 a DerivedDerived您可以为from添加一个构造函数Base来解决此问题。

我会质疑一般设计。从设施继承std通常是设计缺陷/弱点。更喜欢组合而不是继承(特别是如果您打算从中派生的东西不是多态的)。如果需要,可以公开成员,或手动包装其接口SteadyTimetime_point在同一继承层次结构中拥有和使用多个具体(即非抽象)类很快会导致对象切片和其他 UB 等混乱,以及用户的普遍困惑。

于 2019-10-09T12:40:06.413 回答