为什么带有初始化程序的C++17if语句不能按预期工作?
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]
如果具有未推导的占位符类型的变量或函数由表达式 ([basic.def.odr]) 命名,则程序格式错误。但是,一旦在函数中看到了未丢弃的 return 语句,从该语句推导出的返回类型就可以在函数的其余部分中使用,包括在其他 return 语句中。
[示例4:
auto n = n; // error: n's initializer refers to n auto f(); void g() { &f; } // error: f's return type is unknown
为了澄清一点,“声明” ofg2是“可见的”,因为 的定义g1在完整类上下文中。但这并没有扩展到已经看到g2.