gpt4 book ai didi

c++ - 没有可变参数模板的通用分配器类?

转载 作者:太空狗 更新时间:2023-10-29 21:30:31 24 4
gpt4 key购买 nike

我正在尝试编写一个通用分配器类,它在对象空闲时不会真正释放对象的内存(),而是将其保存在队列中,并在请求新对象时返回先前分配的对象。现在,我想不通的是如何在使用我的分配器时将参数传递给对象的构造函数(至少不求助于可变参数模板)。我想出的 alloc() 函数看起来像这样:

template <typename... T>
inline T *alloc(const &T... args) {
T *p;

if (_free.empty()) {
p = new T(args...);
} else {
p = _free.front();
_free.pop();

// to call the ctor of T, we need to first call its DTor
p->~T();
p = new( p ) T(args...);
}
return p;
}

不过,我需要代码与当今的 C++(以及不支持可变参数模板的旧版 GCC)兼容。有没有其他方法可以将任意数量的参数传递给对象构造函数?

最佳答案

当您需要以 C++0x 之前的编译器为目标时,您需要提供伪可变参数模板,即您需要为每个需要的元数提供一个模板函数:

template<class T> 
T* alloc() {
/* ... */
}

template<class T, class A0>
T* alloc(const A0& a0) {
/* ... */
}

/* ... */

您可以使用 preprocessor metaprogramming尽管要处理重复,例如通过使用 Boost.Preprocessor或者使用简单的脚本简单地生成函数。

下面是一个使用 Boost.PP 的简单例子:

#include <boost/preprocessor/arithmetic/inc.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>

template<class T>
T* alloc() {
return new T;
}

#define FUNCTION_ALLOC(z, N, _) \
template<class T, BOOST_PP_ENUM_PARAMS_Z(z, BOOST_PP_INC(N), class T)> \
T* alloc(BOOST_PP_ENUM_BINARY_PARAMS_Z(z, BOOST_PP_INC(N), const T, &p)) { \
return new T( \
BOOST_PP_ENUM_PARAMS_Z(z, BOOST_PP_INC(N), p) \
); \
}

BOOST_PP_REPEAT(10, FUNCTION_ALLOC, ~)

#undef FUNCTION_ALLOC

这会为您生成最多 10 个参数的 alloc() 模板函数。

关于c++ - 没有可变参数模板的通用分配器类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2600416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com