2016-08-09 4 views

答えて

3

サプライヤーは、関数は引数を取りませんし、いくつかのタイプを返すです:

#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>(); 
    } 
); 

注:メーカーは、オブジェクトではなくポインタを返しますので、オペレータ< <への呼び出しは、変更する必要があります。

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クラスを使用することができます。

+0

Ofcサプライヤは、値で渡すことは、実装オブジェクトをスライスし、参照によって渡すことを推奨します。派生クラスがgetを実装する場合に使用します。 –

+0

@ TheSombreroKid Thnx、fixed。 – Nikita

関連する問題