我有一个内存分配器,它为一个对象分配内存并使用任何给定的参数调用它的构造函数,见下文。
// 0 args to constructor
template <class T>
inline T* AllocateObject() { return new (InternalAllocate(sizeof(T), alignof(T))) T(); }
// 1 args to constructor
template <class T, typename arg0>
inline T* AllocateObject(const arg0& a0) { return new (InternalAllocate(sizeof(T), alignof(T))) T(a0); }
template <class T, typename arg0>
inline T* AllocateObject(arg0& a0) { return new (InternalAllocate(sizeof(T), alignof(T))) T(a0); }
// 2 args to constructor
template <class T, typename arg0, typename arg1>
inline T* AllocateObject(arg0& a0, arg1& a1) { return new (InternalAllocate(sizeof(T), alignof(T))) T(a0,a1); }
template <class T, typename arg0, typename arg1>
inline T* AllocateObject(const arg0& a0, arg1& a1) { return new (InternalAllocate(sizeof(T), alignof(T))) T(a0,a1); }
template <class T, typename arg0, typename arg1>
inline T* AllocateObject(arg0& a0, const arg1& a1) { return new (InternalAllocate(sizeof(T), alignof(T))) T(a0,a1); }
template <class T, typename arg0, typename arg1>
inline T* AllocateObject(const arg0& a0, const arg1& a1) { return new (InternalAllocate(sizeof(T), alignof(T))) T(a0,a1); }
//.........
如您所见,调用次数随着参数数量的增加而迅速增加。我必须为每个参数交替使用“const”和“non-const”,以确保它与我传递的任何参数都能正常工作。 (具体来说,能够通过引用传递以及通过值传递)
有没有比重复这个方案更好的方法来执行相同的任务?基本上,我正在考虑最多 8-10 个参数,但我觉得这不太可行。
谢谢
最佳答案
您可以使用可变参数模板。
template <class T, class... Args>
inline T* AllocateObject(Args&&... args) {
return new (InternalAllocate(sizeof(T), alignof(T)))
T(std::forward<Args>(args)...);
}
std::forward
调用将保留任何引用和const
ness。
请注意,这需要 C++11。大多数最新的编译器已经支持可变参数模板(不过我不确定 Microsoft 的)。
关于c++ - 自定义内存分配器设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12202659/