c++ - 在扣除自动之前不能使用捕获的变量

标签 c++ lambda c++14

这个问题与这个one有关.

为什么不编译:

int main() {
    auto foo = [&]() -> int {foo; return {};}();
    (void)(foo);
}

LIVE on Coliru

错误:

main.cpp: In lambda function:
main.cpp:3:30: error: use of 'foo' before deduction of 'auto'
     auto foo = [&]() -> int {foo; return {};}();
                              ^~~

但是将 foo 转换为结果类型允许编译:

int main() {
    auto foo = [&]() -> int {int(foo); (void)(foo);return {};}();
    (void)(foo);
}

LIVE on Coliru

最佳答案

烦人的再次解析。如果某物可以是声明,它就是声明。

int(foo);int (foo);int foo;。那么(void)(foo);中的foo就是指int


第一个片段遇到了 [dcl.spec.auto]/10 :

If the type of an entity with an undeduced placeholder type is needed to determine the type of an expression, the program is ill-formed.

需要 foo 的类型来确定 lambda 体内表达式 foo 的类型,但此时您还没有推导出 foo 的类型,所以程序格式错误。

关于c++ - 在扣除自动之前不能使用捕获的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43054365/

相关文章:

c++ - ffmpeg 调试

c++ - 在 C++ 中新建/删除奇怪的内存泄漏

c++ - 通用引用的标准/官方名称是什么?

c++ - 删除了默认构造函数。仍然可以创建对象...有时

c++ - C++14 中的网络库

c++ - 使用 pugixml 将现有的 xml_node 附加到另一个

c++ - 在 C++ 中使用 matio 时 Mat_Open 不工作

C++ 使用 std::accumulate 生成 map<int,int>

python - 我可以使用 map 将参数元组(或列表)插入到函数中吗?

c# - 使用 Linq 求和嵌套值