使用不同的模板参数包装模板类

Wrap template classes with different template argument

本文关键字:参数 包装      更新时间:2023-10-16

我想写一个线程池,在线程池中我有任务队列。每个任务都是具有不同结果类型的委托。

我想在线程池队列中插入这些委托,但因为每个委托都有不同的模板参数,所以这是不可能的。

我想要一种方法,用不同的模板参数包装这些委托,这样我就可以将它们插入队列中。

将获得任务的线程池的函数:

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)> }

尝试使用Boost Anyboost::任何

我找到了一个解决方案:

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