C++ 稳定时钟::now()返回类型对gcc无效
我有以下代码:C++ 稳定时钟::now()返回类型对gcc无效,c++,c++17,visual-studio-2019,gcc8,C++,C++17,Visual Studio 2019,Gcc8,我有以下代码: #include <chrono> struct SteadyTime : std::chrono::steady_clock::time_point { using time_point::time_point; static SteadyTime now() { return clock::now(); } }; #包括 结构稳定时间:标准::时钟::稳定时钟::时间点{ 使用时间点::时间点; 静态稳定时间now(){
#include <chrono>
struct SteadyTime : std::chrono::steady_clock::time_point {
using time_point::time_point;
static SteadyTime now() {
return clock::now();
}
};
#包括
结构稳定时间:标准::时钟::稳定时钟::时间点{
使用时间点::时间点;
静态稳定时间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
:在静态成员函数“static SteadyTime SteadyTime::now()”中:
:7:24:错误:无法将“std::chrono::”std::chrono::”std::chrono::”stud V2::staddy_clock::time_point“{aka'std::chrono::time_point}转换为“SteadyTime”
返回时钟::现在();
~~~~~~~~~~^~
返回的编译器:1
这段代码似乎是标准的,所以可能会有什么问题?您试图做的基本上是:
struct Base
{};
Base getBase();
struct Derived : Base
{
static Derived get() { return getBase(); }
};
这不起作用,因为编译器不知道如何将基
转换为派生
。您可以为Derived
fromBase
添加构造函数来修复此问题
不过,我会质疑总体设计。从
std
设施继承通常是设计缺陷/弱点。更喜欢组合而不是继承(特别是如果您打算从中派生的东西不是多态的)。如果需要,让稳定时间
公开时间点
成员,或手动包装其界面。在同一继承层次结构中拥有和使用多个具体(即非抽象)类很快会导致像对象切片和其他UB一样的混乱,以及用户的普遍困惑。您不能隐式(或显式)将基本对象转换为派生对象。。。在不使用chrono
或类似工具的情况下尝试它,只需struct A:B{}代码>。(源自非多态std
设施通常也是一个设计缺陷。)使用VS编译时,请确保将一致性模式设置为Yes(/permissive-)。这使编译器更符合标准(关闭许多非标准扩展)