我有别人的代码,我不应该修改:
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中编译它(使用/std:C++-最新版本)时,标记的ctors给出了一个错误:
E2433: constexpr constructor must initialized direct base class它仍然编译(尽管报告这是错误,而不是警告)。它还在g++ 10 (使用-std=c++2a)中编译得很好。
(另外,我可以通过显式调用父程序的默认ctor来消除错误-但是我不认为这应该是必需的吗?
constexpr Child() : Parent () {}
constexpr Child(int t1, int t2) : Parent () { thing1 = t1; thing2 = t2; })
那么,对于C++20标准,谁是对的: VS还是g++?是否有一种经过批准的方法可以在继承(或作为成员变量)继承(或合并为成员变量)时给我的类constexpr ctors一个没有constexpr ctors的基类?
发布于 2020-06-07 12:59:50
直到c++20,Parent类才是可构造的,因为数据成员没有默认的初始化器。我相信是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上下文中默认初始化普通默认可构造类型(例如ints)。有关基本原理,请参阅此纸。
因此,您的代码应该在c++20中编译,但是与许多这样的特性一样,一些编译器可能还没有实现它。
https://stackoverflow.com/questions/62245622
复制相似问题