c++ - 为什么带有初始化程序的 C++17 if 语句不能按预期工作?
问题描述
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
为了补充一点说明,“声明”g2
是“看到”的,因为定义g1
是在完整类上下文中。但这并没有扩展到看到 的定义g2
。
推荐阅读
- javascript - 如何使用 styled-components 和 React 有效地为组件添加变体
- python - 计算具有相同长度的两个数据帧的 RMSE
- python - 如何更改 matplotlib 工具栏的平移和缩放按钮的模式
- php - Laravel 同时使用 2 个 api 级别,彼此分开
- c++ - 在 Eclipse 编辑器中为单个文件强制执行特定的语法突出显示
- r - 在 R 中使用 100 多个特征 lm 函数
- driver - Linux 函数 i2c ds1307_probe 未调用
- image-processing - 使用python自己实现二进制阈值但得到错误的结果
- android - 无法从图库中选择图像
- python - 有没有办法在 Python 3.6 中将列表输入到以 *args 作为其参数的函数中?