我试图利用C ++ 0x闭包来使自定义词法分析器和解析器之间的控制流更简单。没有闭包,我有以下安排:

//--------
// lexer.h
class Lexer {
public:
  struct Token { int type; QString lexeme; }
  struct Callback {
    virtual int processToken(const Token &token) = 0;
  };
  Lexer();
  int tokenize(const QList<Token> &patterns, QTextStream &stream,
               Callback *callback);
};
//-------------
// foo_parser.h
class FooParser: public Lexer::Callback {
  virtual int processToken(const Lexer::Token &token);
  int process(QTextStream *fooStream);
  // etc..
}
//--------------
// foo_parser.cc
int FooParser::processToken(const Lexer::Token &token) {
  canonicalize(token);
  processLine();
  return 0;
}
int FooParser::process(QTextStream *fooStream) {
  Lexer lexer;
  // *** Jumps to FooParser::processToken() above! ***
  return lexer.tokenize(patterns_, fooStream, this);
}


上面的代码的主要问题是,我不喜欢从lexer.tokenize()调用到FooParser :: processToken()函数的控制流中的“跳转”。

我希望闭包将允许这样的事情:

int FooParser::process(QTextStream *fooStream) {
  Lexer lexer;
  return lexer.tokenize(patterns_, fooStream, [&](const Lexer::Token &token) {
    canonicalize(token);
    processLine();
    return 0;
  });
  // ...
}


至少对我而言,要通过lexer.tokenize()调用哪些FooParser方法要更加清楚。

不幸的是,我在C ++ 0x闭包中看到的唯一例子是这样的:

int total = 0;
std::for_each(vec.begin(), vec.end(), [&total](int x){total += x;});
printf("total = %d\n", total);


虽然可以使该示例代码正常工作,但我仍无法弄清楚如何编写像std :: for_each()这样的函数,该函数将Functor / closure作为参数并调用它。

也就是说,我不确定如何编写类Foo来做到这一点:

// Does this need to be templated for the Functor?
struct Foo {
  void doStuff( ... what goes here?????? ) {
    myArg();
  }
};

int someNumber = 1234;
Foo foo;
foo.doStuff([&]() { printf("someNumber = %d\n", someNumber); }


对于此示例,预期输出为someNumber = 1234

供参考,我的编译器是gcc版本4.5.1。

非常感谢。

最佳答案

doStuff可以采用std::function

void doStuff(std::function<void()> f)
{
    f();
}


使用模板是另一种选择:

template <typename FunctionT>
void doStuff(FunctionT f)
{
    f();
}


lambda表达式的实际类型是唯一且未指定。

关于c++ - C++ 0x闭包/lambdas示例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4001582/

10-13 08:34