开发者

C++0x closures / lambdas example

I am attempting to leverage C++0x closures to make the control flow between a custom lexer and parser more straightforward. Without closures, I have the following arrangement:

//--------
// 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);
}

The main issue I have with the above code is that I don't like the "jump" in control flow from the lexer.tokenize() call to the FooParser::processToken() function.

I am hoping that closures will allow something like this:

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

At least to me, it's a lot more clear what FooParser methods will be invoked via lexer.tokenize() .

Unfortunately the only examples I have seen with C++0x closures go something like this:

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

And while I can get this example code to work, I have been unable to figure out how to write a function like std::for_each() that takes a Functor/closure as an argument and invokes it.

That is to say, I'm not sure how to write a class Foo such that I can do this:

// 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); }

For this example, the expected output would be someNumber = 1234

For reference, my compiler is gcc version 4.5.1 .

Many thanks.


doStuff can take a std::function:

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

Using a template is another option:

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

The actual type of the lambda expression is unique and unspecified.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜