没有一种语言特性可以替代可变参数模板(当然,否则它们就不会被发明出来)。
您可以提供几个重载函数,每个函数接受多达 N
个参数(对于合理的 N
选择)。每个重载函数将完美转发其参数到 T
的构造函数中。
因此,除了空函数模板之外:
template <class T>
T *allocate()
{
T *obj = new(top) T();
top += sizeof(T);
return obj;
}
You will have a unary function template:
template <class T, class P1>
T *allocate(P1&& p1)
{
T *obj = new(top) T(std::forward<P1>(p1));
top += sizeof(T);
return obj;
}
一个二元函数模板:
template <class T, class P1, class P2>
T *allocate(P1&& p1, P2&& p2)
{
T *obj = new(top) T(std::forward<P1>(p1), std::forward<P2>(p2));
top += sizeof(T);
return obj;
}
一个三进制函数模板:
template <class T, class P1, class P2, class P3>
T *allocate(P1&& p1, P2&& p2, P3&& p3)
{
T *obj = new(top) T(std::forward<P1>(p1), std::forward<P2>(p2),
std::forward<P3>(p3));
top += sizeof(T);
return obj;
}
等等(你明白的)。如果你关心代码复制,你可以想出一些宏来减轻痛苦 - 但是它们并不能完全消除痛苦,特别是如果你不喜欢宏。
不要忘记:
要使用std::forward<>()
,您需要访问它。