首页 > 解决方案 > 为什么带有初始化程序的 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 语句不能按预期工作?

标签: c++c++17language-lawyerautotype-deduction

解决方案


因为标准是这样说的(引用最新草案):

[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


推荐阅读