且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是java.util.function.Supplier的C ++等价物?

更新时间:2021-08-30 04:00:48

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.