使用 c++14 构建时可用的 pack fold 表达式(c++17 扩展)

pack fold expression (c++17 extension) available when building with c++14

以下代码包含一个折叠表达式,afaiu 是一个 c++17 特性:

template <typename... T> static bool variable_length_or(const T ... v) {
  return (v || ...);
}

bool foo () {
   return variable_length_or(true, false, true, false);
}

我觉得奇怪的是,在使用 -std=c++14 (compiler-explorer) 构建时,g++ 和 clang++ 似乎都适用。他们确实创建了一个警告:

<source>:2:16: warning: pack fold expression is a C++17 extension [-Wc++17-extensions]

 return (v || ...);

这有点说明我写的东西在c++17之前是不行的,但是编译成功了,代码似乎做了它应该做的。我本以为编译会失败。

关于为什么编译器接受我的折叠表达式的任何解释?

(归功于应得的功劳:我从 this question, and I could check if all T are bool similar to what is suggested 中获得灵感)

如果您不添加 -ansi -pedantic 等内容以严格遵守标准,编译器可以自由采用某些扩展,或者在本例中采用以下标准的元素。

-ansi -pedantic 是我为 g++ 和 clang++ 添加的选项;显然,其他编译器可以使用不同的选项。

-- 编辑--

正如 Barry 所指出的(谢谢!),-ansi 不再有用并且足够了 -pedantic

正如 Passer By 所指出的(谢谢!),如果不严格遵守,使用 -pedantic-error 来施加错误可能很有用,而不仅仅是警告。

符合标准的 C++17 编译器必须提供折叠表达式。但这是一个有用的语言特性,是否值得主动 禁用 它只是因为你在以前的语言模式下编译?

允许实现提供扩展,前提是它们不会改变格式良好的程序的行为 ([intro.compliance]/8)。 C++17 之前的折叠表达式就是这样一种扩展——它们纯粹是附加的。因此,作为在 C++14 模式下允许和禁止折叠表达式之间的效用权衡问题,gcc 和 clang 似乎都决定倾向于允许。

当然,你不应该依赖 - 如果你想编写 C++17 代码,你应该在 C++17 中编译。如果你需要依赖它的帮助,你可以用 -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.