Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C++ equivalent of a java.util.function.Consumer?

Tags:

java

c++

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?

like image 704
DuffyChan Avatar asked Dec 03 '25 21:12

DuffyChan


2 Answers

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");
like image 165
user253751 Avatar answered Dec 06 '25 09:12

user253751


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.

like image 24
mash Avatar answered Dec 06 '25 10:12

mash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!