c++ - 为什么带有初始化程序的C++ 17 if语句无法按预期工作?

标签 c++ c++17 language-lawyer auto type-deduction

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的定义在完整类上下文中。但这并没有扩展到看到g2的定义。

关于c++ - 为什么带有初始化程序的C++ 17 if语句无法按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67418029/

相关文章:

c++ - obj.template operator() 构造不适用于 xlC 11.1

c++ - 匹配别名模板作为模板参数

c++ - 为什么 GCC 在这里优化分配?

c++ - [dcl.constexpr]/3 中的 contain 是什么意思

c++ - 通过显示错误消息 C++ 和 Qt 自定义异常

c++ - 在 C++ 中使用 `restrict` 类型限定符和 `unique_ptr` 的受限别名

c++ - 如何确定调用堆栈结束?

c++ - 无法在 wxWidgets (C++) 中显示 `𝑥`(UTF-16 字符)

c++ - 如何从可变模板参数中删除元素?

c++ - 结构化绑定(bind) : loop over deque of tuple