c++中与java.util.function. provider等价的是什么?
What is the C++ equivalent of a java.util.function.Supplier?
例如,我有以下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++的等效函数是什么?
provider是一个不带参数并返回某种类型的函数:你可以用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;
}
我在这里没有使用指针,也没有使用operator 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>();
}
);
注意:对操作符<<然后应该修改,因为maker将返回一个指针而不是一个对象。
您可以使用c++模板类来实现目标:
template<typename TR> class Supplier
{
private:
TR (*calcFuncPtr)();
public:
Supplier(TR(*F)())
{
calcFuncPtr = F;
}
TR get() const
{
return calcFuncPtr();
}
};
用法示例:
#include <string>
#include <iostream>
struct Employee
{
public:
std::string ToString()
{
return "A EMPLOYEE";
}
};
Employee maker(const Supplier<Employee>& fx)
{
return fx.get();
}
Employee GetInstanceFunc()
{
return Employee();
}
int _tmain(int argc, _TCHAR* argv[])
{
Employee employee(maker(GetInstanceFunc));
std::cout << employee.ToString();
return 0;
}
maker(GetInstanceFunc)
行隐式类型转换允许使用Supplier
类而不需要显式的模板实例化。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- C++避免重复声明的语法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- C++中名称篡改的目的是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 派生类销毁的最佳实践是什么
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 通过JNI传递数据数组的最快方法是什么
- "using namespace std;"在C++的作用是什么?
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 文件系统:复制功能的速度秘诀是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 是什么原因导致它无法编译?它是声明签名还是在函数本身的实现中
- c++中与java.util.function. provider等价的是什么?