2013-11-21 51 views
0

我想寫一個線程池,並且在線程池中我有任務隊列。 每個任務都是具有不同結果類型的委託。用不同的模板參數換行模板類

我想在線程池隊列中插入這個委託,但是因爲每個委託都有不同的模板參數,所以這是不可能的。

我想要一個方法來包裝這個委託與不同的模板參數,以便我可以插入隊列中。線程池的

功能,將讓任務:

Queue<Delegate<?()>> workQueue; // Can't use specific type 

template<typename R> 
Task<R> doWork(Delegate<R(void)> del) 
{ 
    workQueue.pushBack(del); // Can't do this 
} 

或者是這樣的僞代碼:

Array{ Delegate<void(void)>, Delegate<int(void)>, Delegate<MyClass(void)> } 

回答

2

嘗試使用升壓任何 的boost ::任何

+0

我沒有提升,現在我不想使用它 – MRB

0

我找到了解決方案:

class FunctionWrapper 
{ 
private: 

protected: 
    class ImpBase 
    { 
    public: 
     virtual ~ImpBase() {} 
     virtual void call() abstract; 
    }; 

    template<typename F> 
    class Imp : public ImpBase 
    { 
    public: 
     typename F FunctionType; 

     FunctionType mFunc; 

     Imp(FunctionType&& pFunc) : mFunc(std::move(pFunc)) {} 
     ~Imp() {} 

     void call() override { mFunc(); } 
    }; 

    std::unique_ptr<ImpBase> mPtr; 

public: 
    FunctionWrapper() = default; 
    FunctionWrapper(const FunctionWrapper&) = delete; 
    template<typename F> 
    FunctionWrapper(F&& pFunc) : mPtr(new Imp<F>(std::move(pFunc))) {} 

    FunctionWrapper& operator =(const FunctionWrapper&) = delete; 
    FunctionWrapper& operator =(FunctionWrapper&& pOther) { mPtr = std::move(pOther.mPtr); } 

    void operator()() { mPtr->call(); } 
}; 
相關問題