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

时间:2016-08-09 05:40:07

标签: java c++

例如,我有以下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 ++的等价物是什么?

2 个答案:

答案 0 :(得分:4)

供应商是一个不带参数并返回某种类型的函数:您可以用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;
}

我没有在这里使用指针,也没有使用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>();
    }
);

注意:对运营商的调用&lt;&lt;然后应该修改,因为maker将返回一个指针而不是一个对象。

答案 1 :(得分:1)

您可以使用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类。

相关问题