c++ - 模板 lambda 有时无法编译

标签 c++ c++11 lambda

我想为我的 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)?

最佳答案

如果您不使用非静态数据成员初始化程序来初始化f,gcc-4.8.1 会编译代码

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->longest,它甚至可以工作。

关于c++ - 模板 lambda 有时无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23943439/

相关文章:

c++ - constexpr 唯一标识,使用 clang 编译但不使用 gcc

c++ - 错误是什么?Q-确定并打印给定 n 值的以下谐波级数之和。(1+1/2+1/3+........+1/n)

c++ - Visual Studio调试优化如何工作?

c++ - GNU make 中没有 make XXX 错误的规则

c++11 - MS ACCESS 中的 GRANT 支持

c# - 从 int[] 中选择每 2 个 int 并使用 Lamda 表达式将它们组合成一个 uint64[] 数组

javascript - 在 JavaScript 中,我可以检查是否可以在不实际评估字符串的情况下评估它吗?

c# - 在 Expression<Func<TModel, Object>> 中评估参数结果

c++ - 错误 C2893 : Failed to specialize function template 'unknown-type std::less<void>::operator ()(_Ty1 &&,_Ty2 &&) const'

c++ - 基于范围的 for 循环表达式中的临时可选