从lambda表达式无效使用非静态数据成员

时间:2014-04-26 14:11:02

标签: c++11 lambda

我希望有一个std :: function来记住它的状态。所以我试过这个:

#include <iostream>
#include <functional>

class Dots {
public:
  Dots(std::ostream & sink) :  out_stream(sink) {}

  std::function<void(const int n)> show = [this](int n) {
    level+=n;
    for (int i = 0; i < level; i++) out_stream << "*";
    out_stream << "\n";
  };

  std::ostream & out_stream;
  int level = 0;
};


int main() {

  Dots d(std::cerr);
  d.show(3);
  d.show(1);

  return 0;
}

这与clang(Apple LLVM 5.0版)一起编译,但它不适用于gcc 4.7.3。后者说:错误:无效使用非静态数据成员'Dots :: level'。任何人都可以解释我如何使它工作吗?

我的最终目标是制作一个我将用作访问者的通用方法。所以在真实情况下我会有我的


template 
void traverse_depth_first(N root,A previsit_action,A invisit_action,A postvisit_action);

类型 A 是我正在尝试创建的std :: function对象。我认为lambdas会对此有好处,因为它们可以很容易地在现场创建访问方法。

修改 所以我应用了Kerrek SB的答案,上面的代码用gcc和clang编译。但它没有icc 14.0.2,它抱怨

error: "this" cannot be used inside the body of this lambda

有人能解释我为什么吗?

0 个答案:

没有答案
相关问题