For example, I have the following Java code:
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Consumer<String> c = (x) -> System.out.println(x.toLowerCase());
c.accept("Java2s.com");
}
}
What will be the C++ equivalent?
Use std::function<void(const std::string&)>.
You can initialize instances of this from function pointers, or from lambdas, e.g.:
void foo(const std::string &s) {
std::cout << s << std::endl;
}
// later
std::function<void(const std::string &)> c = foo;
c("Java2s.com");
or
std::function<void(const std::string &)> c = [](const std::string &) {
std::cout << s << std::endl;
};
c("Java2s.com");
If you really miss accept. You could also implement that:
#include <functional>
#include <iostream>
#include <string>
template <class Food>
class Consumer {
private:
std::function<void(Food)> consume_;
public:
template <class Eater>
Consumer<Food>(Eater consume) : consume_(consume){};
void accept(Food food) { consume_(food); }
};
// Usage
int main() {
Consumer<const std::string&> consumer([](
const std::string& out) { std::cout << out << '\n'; });
consumer.accept("My lovley string.");
consumer.accept("Will be eaten!");
}
Or you could even:
template <class Food>
class Consumer {
public:
std::function<void(Food)> accept;
template <class Eater>
Consumer<Food>(Eater consume) : accept(consume){};
};
if you want to be able to swap out accept on the fly.
In other words I don't understand why a consumer exists in Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With