使用不同的模板参数包装模板类
Wrap template classes with different template argument
我想写一个线程池,在线程池中我有任务队列。每个任务都是具有不同结果类型的委托。
我想在线程池队列中插入这些委托,但因为每个委托都有不同的模板参数,所以这是不可能的。
我想要一种方法,用不同的模板参数包装这些委托,这样我就可以将它们插入队列中。
将获得任务的线程池的函数:
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(); }
};
相关文章:
- 考虑引用和常量的可变参数函数包装器
- 将对象传递给函数而不将其包装到 std::ref 中,而参数被指定为 const 引用
- 如何将参数包装在 C 或 C++ 中并将它们传递给系统或 exec*
- 线程构造函数周围的可变参数模板包装器无法编译
- 具有值包装器的可变参数模板构造函数的类构造函数优先级
- 如何解开参数包包装器?
- 用输出参数包装一个c++函数,以便在javascript/node中使用
- JNI Java包装:如何传递byte[]参数
- 将可变参数模板包装到元组向量
- 如何在 C 中包装C++具有参数的类方法或返回另一个C++类的实例?
- 如何将包装类的对象用作包装函数中的参数
- 对类型的非常量左值引用 - 使用类类型的参数时,目标C++包装器中的错误
- pybind11:如何包装以 std::vector<double> 为参数以避免数据复制的 C++ 函数
- 如何在 SWIG 中包装可变参数模板类的可变参数模板成员函数?
- Boost Python - 用参数包装构造函数
- 重构现有包装类,以使用与包装器本身相同的构造函数参数包装 T
- NPAPI调用参数包装
- 使用不同的模板参数包装模板类
- 根据Template参数包装类型的容器的Template类
- C++用变量参数包装包装宏