【问题标题】:Compilation error with template and lambda with Clang使用 Clang 的模板和 lambda 编译错误
【发布时间】:2015-05-09 06:33:23
【问题描述】:

我试图用这样的代码编译一个项目

#include <tuple>
#include <utility>

struct Foo
{
};

template <typename... Args>
void start(Args&&... args) {
    auto x = [args = std::make_tuple(std::forward<Args>(args)...)] () mutable {
            auto y = [args] () mutable {
                auto z = [] (Args&&... args) {
                    return new Foo(std::forward<Args>(args)...);
                };
            };
    };
}

int main()
{
    start(Foo{});
}

它似乎在 GCC 4.9.1 中编译得很好,但在 Clang 3.4、3.5、3.6 中却没有。错误信息是

错误:无法在 lambda 中隐式捕获变量“args” 未指定捕获默认值

这是一个编译器错误吗?如果是这样,是否有任何解决方法可以让它在 Clang 上编译?

【问题讨论】:

标签: c++ c++14 clang++


【解决方案1】:

简化为:

template <typename T>
void start(T t) {
    [a = t] { [a]{}; };
}

int main()
{
    start(0);
}

哪个generates the same error in non-trunk versions of clang

这似乎是由a bug in Clang's handling of a non-init-capture of an init-capture 引起的。昨天,5 月 7 日,上述 bug 已修复,当前的 Clang 主干版本可以正确编译上述代码。

由于此错误仅针对 init-capture 的非 init-capture 出现,一个简单的解决方法是在内部 lambda 中也使用 init-capture - 而不是 [a],而是使用 [a = a]

【讨论】:

  • 我很好奇:你是怎么找到那个错误报告的?
  • @dyp 我在所有 Clang 错误中搜索“capture init-capture”。这是列表中的第一项。
  • 我之前尝试使用确切的错误消息进行搜索,但没有找到任何相关信息。
  • @Nat 除非你知道要找什么,否则很难找到 :)
猜你喜欢
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多