为什么带有初始化程序的 C++17 if 语句不能按预期工作?
Why does C++17 if statement with initializer not work as expected?
struct A
{
auto g1()
{
return true;
}
void f()
{
if (auto b = g1(); b) // ok
{
return;
}
if (auto b = g2(); b) // error: use of 'auto A::g2()' before deduction of 'auto'
{
return;
}
}
auto g2()
{
return true;
}
};
为什么带有初始化器的 C++17 if 语句不能按预期工作?
因为标准是这么说的(引用最新草案):
[dcl.spec.auto.general]
If a variable or function with an undeduced placeholder type is named
by an expression ([basic.def.odr]), the program is ill-formed. Once a
non-discarded return statement has been seen in a function, however,
the return type deduced from that statement can be used in the rest of
the function, including in other return statements.
[Example 4:
auto n = n; // error: n's initializer refers to n
auto f();
void g() { &f; } // error: f's return type is unknown
为了澄清一点,g2
的“声明”是“可见的”,因为 g1
的定义在完整的 class 上下文中。但这并没有扩展到看到 g2
.
的定义
struct A
{
auto g1()
{
return true;
}
void f()
{
if (auto b = g1(); b) // ok
{
return;
}
if (auto b = g2(); b) // error: use of 'auto A::g2()' before deduction of 'auto'
{
return;
}
}
auto g2()
{
return true;
}
};
为什么带有初始化器的 C++17 if 语句不能按预期工作?
因为标准是这么说的(引用最新草案):
[dcl.spec.auto.general]
If a variable or function with an undeduced placeholder type is named by an expression ([basic.def.odr]), the program is ill-formed. Once a non-discarded return statement has been seen in a function, however, the return type deduced from that statement can be used in the rest of the function, including in other return statements.
[Example 4:
auto n = n; // error: n's initializer refers to n auto f(); void g() { &f; } // error: f's return type is unknown
为了澄清一点,g2
的“声明”是“可见的”,因为 g1
的定义在完整的 class 上下文中。但这并没有扩展到看到 g2
.