[英]C++ lambdas, “error: expected expression”
I'm trying to reproduce java's streams API in C++, and have made this program so far. 我正在尝试用C ++重现java的流API,并且到目前为止已经制作了这个程序。
#include <iostream>
using namespace std;
template <typename E>
class stream {
virtual void collect(void (*consumer) (E)) = 0;
virtual bool anyMatch(bool (*predicate) (E)) {
bool found = false;
collect([&found](E obj) -> { if (predicate(obj)) {found = true} });
return found;
}
};
int main() {
return 0;
}
But when I try to compile it with g++: 但是当我尝试用g ++编译它时:
What am I doing wrong the lambda? 我做错了什么lambda? It is supposed to provide a function (the consumer) which will test the given E with the predicate (a function), and if it yields true, set found to true. 它应该提供一个函数(使用者),它将使用谓词(函数)测试给定的E,如果它产生true,则将find设置为true。
There are a few separate issues in your code: 您的代码中存在一些单独的问题:
The error you posted suggests that you're compiling in pre-C++11 mode. 您发布的错误表明您正在以C ++ 11之前的模式进行编译。 Lambdas were introduced in C++11. Lambda是在C ++ 11中引入的。
There are several syntax errors. 有几个语法错误。 Your lambda trailing return type is missing the type, and you're missing a semicolon in the body of the lambda. 你的lambda尾随返回类型缺少类型,并且你在lambda的主体中缺少一个分号。
You're trying to convert a non-captureless lambda to a function pointer. 您正在尝试将非无捕获的lambda转换为函数指针。 This is impossible, as capturing variables requires a state/context. 这是不可能的,因为捕获变量需要状态/上下文。
Your code is not valid C++ - the syntax is incorrect. 您的代码无效C ++ - 语法不正确。 Here's a version with valid syntax : 这是一个有效语法的版本 :
template <typename E>
class stream
{
virtual void collect(void (*consumer)(E)) = 0;
virtual bool anyMatch(bool (*predicate)(E))
{
bool found = false;
collect([predicate, &found](E obj)
{
if(predicate(obj))
found = true;
});
return found;
}
};
Nevertheless, the code will not compile because non-captureless lambdas cannot be converted to function pointers . 然而,代码将无法编译,因为非无捕获的lambdas无法转换为函数指针 。 If that was allowed, it would be a recipe for disaster, as the information regarding the captured variables will be lost. 如果允许这样做,那将是一个灾难的处方,因为有关捕获的变量的信息将丢失。 You can instead use std::function
, which erases the type of the lambda and works with non-empty capture lists, at the cost of memory/run-time overhead: 您可以使用std::function
来删除lambda的类型并使用非空捕获列表,但代价是内存/运行时开销:
template <typename E>
class stream
{
virtual void collect(std::function<void(E)> consumer)
{
(void)consumer;
}
virtual bool anyMatch(std::function<bool(E)> predicate)
{
bool found = false;
collect([predicate, &found](E obj)
{
if(predicate(obj))
found = true;
});
return found;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.