[英]C++0x closures / lambdas example
我試圖利用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表達式的實際類型是唯一且未指定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.