什么是java.util.function.Supplier的C ++等价物? [英] What is the C++ equivalent of a java.util.function.Supplier?

查看:72
本文介绍了什么是java.util.function.Supplier的C ++等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有以下Java代码:

For example, I have the following Java code:

public class Main {
  public static void main(String[] args) {
    System.out.println(maker(Employee::new));
  }

  private static Employee maker(Supplier<Employee> fx) {
    return fx.get();
  }
}

class Employee {
  @Override
  public String toString() {
    return "A EMPLOYEE";
  }
}

等效的C ++是什么?

What will be the C++ equivalent?

推荐答案

Supplier是一个不带参数并返回某种类型的函数:您可以使用

Supplier is a function taking no arguments and returning some type: you can represent that with std::function:

#include <iostream>
#include <functional>
#include <memory>

// the class Employee with a "print" operator

class Employee
{
    friend std::ostream& operator<<(std::ostream& os, const Employee& e);
};

std::ostream& operator<<(std::ostream& os, const Employee& e)
{
    os << "A EMPLOYEE";
    return os;
}

// maker take the supplier as argument through std::function

Employee maker(std::function<Employee(void)> fx)
{
    return fx();
}

// usage

int main()
{
    std::cout << maker(
        []() { return Employee(); }
            // I use a lambda here, I could have used function, functor, method...
    );

    return 0;
}

我在这里既没有使用指针,也没有使用新的运算符来分配Employee:如果要使用它,则应考虑使用

I didn't use pointers here nor the operator new to allocate Employee: if you want to use it, you should consider managed pointers like std::unique_ptr:

std::unique_ptr<Employee> maker(std::function<std::unique_ptr<Employee>(void)> fx)
{
    return fx();
}

// ...

maker(
    []()
    {
        return std::make_unique<Employee>();
    }
);

注意:呼叫操作员<<然后应进行修改,因为maker将返回指针而不是对象.

Note: the call to operator<< should then be modified because maker will return a pointer instead of an object.

这篇关于什么是java.util.function.Supplier的C ++等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆