gpt4 book ai didi

c++ - 关于在丢弃的 if constexpr(false) 语句中实例化模板时,编译器之间的行为不一致

转载 作者:IT老高 更新时间:2023-10-28 21:56:47 25 4
gpt4 key购买 nike

我试图了解下面的代码段是否应该根据标准编译。当我尝试使用三个主要编译器的最新版本进行编译时,会出现以下情况:

  • Clang(版本 7.0.0,带有 -std=c++17 标志):编译良好;
  • GCC(8.2 版,带有 -std=c++17 标志):也可以正常编译;
  • MSVC(版本 19.16,带有 /std:c++17 标志):编译器错误(见下文)。

出现错误是因为 MSVC 编译器似乎试图实例化 std::optional<void>尽管代码被丢弃。 GCC 和 Clang 似乎没有这样做。

标准是否明确定义了在这种情况下应该发生什么?

#include <optional>  
#include <type_traits>
template<typename T, typename... Args>
struct Bar
{
void foo(Args... args)
{
if constexpr(!std::is_same_v<T, void>) // false
{
// MSVC compiler error occurs because of the line below; no error occurs when compiling with GCC and Clang
std::optional<T> val;
}
}
};
int main(int argc, char** argv)
{
Bar<void, int> inst;
inst.foo(1);
return 0;
}

MSVC 出错:

C:/msvc/v19_16/include\optional(87): error C2182: '_Value': illegal use of type 'void'

C:/msvc/v19_16/include\optional(128): note: see reference to class template instantiation 'std::_Optional_destruct_base<_Ty,false>' being compiled
with
[
_Ty=void
]

Live demo

最佳答案

绝对是 MSVC 的错误。一个 bug report存在,据报道已在 Visual Studio 2019 Preview 中修复。


if constexpr [stmt.if]/2 中标准化:

If the if statement is of the form if constexpr, the value of the condition shall be a contextually converted constant expression of type bool; this form is called a constexpr if statement.

这适用。

If the value of the converted condition is false, the first substatement is a discarded statement, otherwise [...].

它也适用,在你的程序中制作 { std::optional<T> val; }一个丢弃的语句

During the instantiation of an enclosing templated entity (ndYSC Bar<void, int>), if the condition is not value-dependent after its instantiation, the discarded substatement (if any) is not instantiated.

关于c++ - 关于在丢弃的 if constexpr(false) 语句中实例化模板时,编译器之间的行为不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54126957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com