【问题标题】:template lambda sometimes doesn't compile模板 lambda 有时无法编译
【发布时间】:2014-05-29 21:37:29
【问题描述】:

我想为我的 trie 数据结构实现一个通用的访问者模式。以下是给编译器带来麻烦的提取的最小片段:

#include <functional>

struct Node {
    size_t length;
};

template<typename N>
class C {
public:
  size_t longest = 0;
  std::function<void(const N )> f = [this](N node) {
    if(node->length > this->longest) this->longest = node->length;
  };
};

int main() {

  Node n;
  n.length = 5;
  C<Node*> c;
  c.f(&n);
}

它使用 g++ (Ubuntu/Linaro 4.7.2-2ubuntu1)、Ubuntu clang 版本 3.4-1ubuntu3 和 Apple LLVM 版本 5.0 (clang-500.2.79) 编译。 icc (ICC) 14.0.2 说:

try_lambda_T.cc(15): error: "this" cannot be used inside the body of this lambda
  if(node->length > this->longest) this->longest = node->length;

我发现了一个类似的帖子: Class with non-static lambda member can't use default template paramers? 这个故事导致了一个在 g++ 4.8.1 中解决的错误报告: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54764

但是,g++ (Ubuntu 4.8.2-19ubuntu1) 会导致:

internal compiler error: in tsubst_copy, at cp/pt.c:12125
   std::function<void(const N )> f = [this](N node) {
                                        ^
Please submit a full bug report,
with preprocessed source if appropriate.

我能用它做些什么来让它编译最新的 g++(希望是 icc)?

【问题讨论】:

  • 如果您在 lambda 体内使用 longest 而不是 this-&gt;longest,icc 会抱怨吗?您不必说this-&gt;,捕获this 意味着您可以访问类的数据成员。您发现了一个 gcc 错误(内部编译器错误始终是错误),您应该报告它。
  • 我测试了它,longest 而不是this-&gt;longest 的内部错误相同。 g++4.9 OS X.
  • 看起来像一个编译器错误,但是您可以尝试通过引用而不是 this 实例捕获 longest 作为临时解决方法。

标签: c++ c++11 lambda


【解决方案1】:

gcc-4.8.1 编译代码如果你不使用非静态数据成员初始化器来初始化f

template<typename N>
class C {
public:
  C()
  : f([this](N node) {
        if(node->length > longest) longest = node->length;
      })
  {}
  size_t longest = 0;
  std::function<void(const N )> f;
};

Live demo

如果您更愿意在 lambda 正文中将 longest 称为 this-&gt;longest,它甚至可以工作。

【讨论】:

  • 谢谢!它甚至修复了 icc 构建!
猜你喜欢
  • 2019-05-29
  • 1970-01-01
  • 2023-04-04
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多