2010-10-22 103 views
0

我正在嘗試利用C++ 0x關閉來使自定義詞法分析器和解析器之間的控制流更直接。如果沒有關閉,我有以下安排:C++ 0x關閉/ lambdas示例

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

至少對我來說,這是一個很大更清楚FooParser方法將通過lexer.tokenize調用()。

不幸的是我與的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作爲參數並調用它。

也就是說,我不知道如何寫一個類,這樣我可以做到這一點:

// 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。

非常感謝。

回答

3

doStuff可以採取std::function

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

使用模板是另一種選擇:

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

實際類型的lambda表達式的是獨特的和不確定的。