gpt4 book ai didi

c++ - constexpr构造函数必须初始化直接基类(Visual Studio)

转载 作者:行者123 更新时间:2023-12-02 09:53:37 26 4
gpt4 key购买 nike

我有别人不应更改的代码:

struct Parent { int thing1, thing2; };

并想让我继承的类可用于 constexpr:
struct Child: public Parent
{
constexpr Child() {} //error
constexpr Child(int t1, int t2) { thing1 = t1; thing2 = t2; } //error
constexpr Child(const Child& c) = default;
};

当我在Visual Studio(使用/ std:c++-latest)中对此进行编译时,标记的ctor会给出错误:
E2433: constexpr constructor must initialized direct base class

它仍然可以编译(尽管将其报告为错误,而不是警告)。在g++ 10中也可以正常编译(使用-std = c++ 2a)。

(此外,我可以通过显式调用Parent的默认ctor来消除错误-但我认为这不是必须的吗?
    constexpr Child() : Parent () {}
constexpr Child(int t1, int t2) : Parent () { thing1 = t1; thing2 = t2; }

)

因此,对于C++ 20标准,谁是正确的:VS还是g++?有没有一种允许的方法可以给我的类 constexpr ctors,同时继承(或合并为成员变量)没有 constexpr ctors的基类?

最佳答案

在c++ 20之前,您的Parent类不可构造为constexpr,因为数据成员没有默认的初始化程序。我相信这是一个允许其编译的gcc错误。

您可以像这样使Parent constexpr可构造:

struct Parent { int thing1{}, thing2{}; };  // provide default values for members

请注意,您可以要求 Parent的构造函数为constexpr,如下所示:
struct Parent { 
int thing1, thing2;
constexpr Parent() = default;
};

现在gcc也将无法编译该文件。

从c++ 20开始,通过允许在constexpr上下文中对默认的可构造类型(例如 int)进行默认初始化,消除了此限制。有关基本原理,请参见此 paper

因此,您的代码应在c++ 20中编译,但是与许多此类功能一样,某些编译器可能尚未实现。

关于c++ - constexpr构造函数必须初始化直接基类(Visual Studio),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62245622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com