C++20 introduced support for designated initializers.
In g++ with -std=c++17
, one can use designated initializers and as long as you don't leave any out, it will compile without any errors or warnings:
struct Foo {
int a;
float b;
};
Foo f {
.a = 7,
.b = 42.1f,
};
Yet if I enable -Wpedantic
(and -Werror
) the C++17 compiler will spit out:
error: C++ designated initializers only available with '-std=c++20' or '-std=gnu++20' [-Werror=pedantic]
But there does not seem to be a way to disable or suppress this error without disabling -Wpedantic
too, which is far too coarse in my case.
I find this very confounding because there's no warning emitted when using this feature with C++17 - code using it will compile and run, seemingly, with un-undefined behaviour, yet from everything I've found online it's not supposed to be used with C++17.
So why isn't there a warning or error when using this unsupported feature with C++17 without -Wpedantic
? Surely it's not pedantic to warn the user of a non-supported language feature if it's technically UB? And if it's not UB, then it works, right?
Lastly, without recompiling g++, how can I trick the compiler into accepting -Wpedantic
without generating such warnings if I choose to use designated initializers in my C++17 code?
-pedantic
DIRECTS the compiler to diagnose them. Your options are (1) compile as C++20 (2) don't use-pedantic
or (3) don't use designated initialisers – Inexplicable