【问题标题】:Lambda in lambda cannot be a template?lambda 中的 Lambda 不能是模板?
【发布时间】:2017-05-17 16:00:44
【问题描述】:

Visual Studio 编译器 (MSVC 2015) 无法编译以下简单代码:

int main() {
    auto foo = [](auto callback) {
        callback(int{});
    };
    auto rexs = [&foo]() {
        foo([](auto tg) {});
    };
}

它会引发内部编译器错误:

fatal error C1001: An internal error has occurred in the compiler.

VC++ 喜欢在编译的代码包含错误时给出错误C1001(即程序员犯了错误,但 VC++ 只是没有完全识别代码中的错误),所以我想知道我是否可以犯这里有一个错误。

但是,从我所看到的所有角度来看,我的代码看起来都符合标准,而且对我来说这似乎是一个 VC++ 错误。我想对了吗?

【问题讨论】:

  • “编译器出现内部错误。”无论复制代码是否有效,始终是一个错误(在编译器/工具链中)。虽然,当代码有效时,错误更严重。
  • VC++ likes to give error C1001 when the compiled code contains errors (i.e. the programmer made a mistake, but VC++ just doesn't fully recognize the mistake in the code)。即使这是真的,它仍然是编译器错误。如果 VS 认为代码错误,它应该有理由这样认为。
  • @user2079303 我已经在我的项目中多次看到 C1001,因为我犯了一个小的语法错误,以至于我不再费心责骂我的编译器了。
  • @Bernard 你需要一个更好的编译器:)
  • @deviantfan 我希望 VS 2017 会更好:/ 对于 Windows,我没有太多选择,不是吗?

标签: c++ templates lambda c++14 auto


【解决方案1】:

您的代码在 clang 3.8 和 gcc 5.4 (http://rextester.com/SCAH69935) 上编译得很好,所以它似乎是一个 VC++ 错误。

【讨论】:

  • “C1001”始终是一个 VC++ 错误。
  • 它似乎在 VS 2017 在线编译器上编译得很好。 This one.也许是时候升级了。
【解决方案2】:

VC++ 是对的:C++11 不允许在 lambda 中使用 auto。 我们只能在 C++14 之后在 lambda 中使用auto

Clang 3.8.0 使用 -std=c++11 给我这个错误:

main.cpp:7:17: error: 'auto' not allowed in lambda parameter
    auto f = [](auto x) { return x + 1;};

和 gcc 7.1.0(具有相同的标志)给了我这个: main.cpp:在函数'int main()'中:

main.cpp:7:17: error: use of 'auto' in lambda parameter declaration only available with -std=c++14 or -std=gnu++14

     auto f = [](auto x) { return x + 1;};

对于此代码:

int main()
{
    auto f = [](auto x) { return x + 1;};
}

【讨论】:

  • 这不会使“内部编译器错误”正确。
  • 我的标签错了。它应该是 C++14。感谢您指出这一点。
  • 正确,但也不代表代码正确
  • 甚至微软都表示它在 VS 2015 中支持通用 lambda:msdn.microsoft.com/en-us/library/hh567368.aspx
  • 正如伯纳德指出的那样,在我发布答案时,问题的标签是 C++11。 C++11 不允许在 lambda 中使用 auto。只要您为 C++11 编译(并且编译器完全符合 C++11),编译器就不算数。
猜你喜欢
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
相关资源
最近更新 更多