The following code contains a fold expression, which afaiu is a c++17 feature:
template <typename... T> static bool variable_length_or(const T ... v) {
return (v || ...);
}
bool foo () {
return variable_length_or(true, false, true, false);
}
what I find odd is that both g++ and clang++ seem to be fine with it when building with -std=c++14
(compiler-explorer). They do create a warning:
<source>:2:16: warning: pack fold expression is a C++17 extension [-Wc++17-extensions]
return (v || ...);
This somewhat indicates that what I'm writing is not okay before c++17, but the compilation succeeds and the code seems to do what it should. I would've expected the compilation to fail.
Any explanation about why the compiler accepts my fold expression?
(credit where credit is due: I took inspiration from this question, and I could check if all T
are bool
similar to what is suggested here)
A conforming C++17 compiler has to provide fold expressions. But that's a useful language feature, is it worth actively disabling it just because you're compiling in a previous language mode?
Implementations are allowed to provide extensions, provided that they do not alter the behavior of well-formed programs ([intro.compliance]/8). Fold expressions in pre-C++17 are just such an extension - they're purely additive. So as a question of utility tradeoff between allowing and disallowing fold expressions in C++14 mode, it seems that both gcc and clang decided to lean towards allowing.
Of course, you shouldn't rely on this - if you want to write C++17 code, you should compile in C++17. If you want help relying on it, you can compile with -pedantic-errors
:
Give an error whenever the base standard (see -Wpedantic
) requires a diagnostic, in some cases where there is undefined behavior at compile-time and in some other cases that do not prevent compilation of programs that are valid according to the standard. This is not equivalent to -Werror=pedantic
, since there are errors enabled by this option and not enabled by the latter and vice versa.
If you don't add something as -ansi -pedantic
, to impose a strict conformance to the standard, the compilers are free to adopt some extensions or, in this case, elements of the following standard.
-ansi -pedantic
are the options I add for g++ and clang++; other compilers can use different options, obviously.
-- EDIT --
As pointed by Barry (thanks!), -ansi
is no more useful and is enough -pedantic
.
As pointed by Passer By (thanks!), can be useful the use of -pedantic-error
to impose an error, and non only a warning, in case of not strictly conformance.