例如,我有以下 Java 代码:
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++ 的等价物是什么?
供应商是一个不带参数并返回某种类型的函数:您可以用标准::函数:
#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;
}
我在这里没有使用指针,也没有使用 new 运算符来分配 Employee:如果你想使用它,你应该考虑像这样的托管指针std::unique_ptr:
std::unique_ptr<Employee> maker(std::function<std::unique_ptr<Employee>(void)> fx)
{
return fx();
}
// ...
maker(
[]()
{
return std::make_unique<Employee>();
}
);
注意:然后应该修改对operator
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)