I'm trying to reproduce java's streams API in C++, and have made this program so far.
#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++:
What am I doing wrong the 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.
There are a few separate issues in your code:
The error you posted suggests that you're compiling in pre-C++11 mode. Lambdas were introduced in 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.
You're trying to convert a non-captureless lambda to a function pointer. This is impossible, as capturing variables requires a state/context.
Your code is not valid C++ - the syntax is incorrect. 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. 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:
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;
}
};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments