gpt4 book ai didi

C++0x 闭包/lambda 示例

转载 作者:行者123 更新时间:2023-11-28 01:09:50 25 4
gpt4 key购买 nike

我正在尝试利用 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() 的函数,它需要一个仿函数/闭包作为参数并调用它。

也就是说,我不确定如何编写一个类 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++0x 闭包/lambda 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4001582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com