模板lambda有时不编译

时间:2014-05-29 21:37:30

标签: 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)吗?

1 个答案:

答案 0 :(得分:2)

如果您不使用非静态数据成员初始化程序来初始化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,它甚至可以工作。