c++ - 使用部分 NSDMI 聚合 constexpr 默认构造函数错误
问题描述
我在下面有一个简单的结构,用于具有聚合初始化语法的常量表达式。test::c
现在,由于NSDMI,我想将其设为可选,但这会在 gcc 和 clang 的常量表达式上下文中触发默认构造函数的错误。
我不明白为什么隐式默认构造函数在第一种情况下默认初始化所有成员,但不使用 NSDMI。如果我为所有成员设置默认值没有错误,但这不是我想要的。此外,我不能声明默认构造函数,因为该结构将不再是聚合。
- 在这两种情况下如何隐式生成默认构造函数?有标准规则吗?
- 有没有办法修复错误并保存警告[-Wmissing-field-initializers]?
#include "debug.h"
struct test {
//OK
/* int a, b, c; */
/* int a=0, b=0, c=3; */
//ERROR
int a, b, c=3;
};
int main(){
const test val1 = test(); //{0,0,3}
constexpr test val2 = test(); //error: call to non-'constexpr' function 'test::test()'
constexpr test val3 = {}; //{0,0,3}
constexpr test val4 = {1}; //warning: missing initializer for member 'test::b'
constexpr test val5 = {1,2}; //{1,2,3}
}
输出 :
test.cpp: In function 'int main()':
test.cpp:13:32: error: call to non-'constexpr' function 'test::test()'
constexpr test val2 = test();
^
test.cpp:3:8: note: 'test::test()' is not usable as a 'constexpr' function because:
struct test {
^~~~
test.cpp:8:9: note: defaulted default constructor does not initialize 'int test::a'
int a, b, c=3;
^
test.cpp:8:12: note: defaulted default constructor does not initialize 'int test::b'
int a, b, c=3;
^
test.cpp:15:29: warning: missing initializer for member 'test::b' [-Wmissing-field-initializers]
constexpr test val4 = {1};
^
谢谢您的帮助。
解决方案
推荐阅读
- typescript - typeorm 错误:重复键值违反唯一约束
- sql - 数据库设计:如何处理取消订单但保存订单历史
- qgis - QGIS 3.16.6:无法加载 SIP 模块
- mysql - 如何在 mySQL 中约束由两列组成的主键,以便一列可以包含三个或更少条目?
- computer-vision - 逐像素回归。如何从 Nx1xHxW 到 Nx3xHxW?
- python - 未解决的参考“graphene_django”
- reactjs - 反应表多选过滤器不过滤数据
- node.js - Access-Control-Allow-Origin 阻止了我的帖子,但我允许了
- python - 你能在 python 中“嵌套”模块吗?
- python - ValueError:无法将字符串转换为浮点数:'what'(Sklearn),如何使用标签编码器?