サプライヤーは、関数は引数を取りませんし、いくつかのタイプを返すです:
#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演算子は、従業員を割り当てるために:あなたはstd::functionていることを表すことができ、使用したい場合それは、あなたがstd::unique_ptrのようにポインタを管理し検討する必要があります。
std::unique_ptr<Employee> maker(std::function<std::unique_ptr<Employee>(void)> fx)
{
return fx();
}
// ...
maker(
[]()
{
return std::make_unique<Employee>();
}
);
注:メーカーは、オブジェクトではなくポインタを返しますので、オペレータ< <への呼び出しは、変更する必要があります。
Ofcサプライヤは、値で渡すことは、実装オブジェクトをスライスし、参照によって渡すことを推奨します。派生クラスがgetを実装する場合に使用します。 –
@ TheSombreroKid Thnx、fixed。 – Nikita